Martyn

Martyn Bullerwell's Blog

XML and LINQ

LINQ and XML can be used to construct, write and read XML in any .NET language.  It simplifies XML reading and writing WITHOUT using XPATH or XSLT.  Don't get me wrong, this does not replace legacy functions from the XML class library, merely overlaps the functionality and eases development. One aspect of LINQ to XML is that it supports writing Query Expressions and can be combined with any of the other LINQ technologies to create or use XML data as a source or destination format.

Creating a new XML file with LINQ, some key elements and required:

XDocument
XElement
XAttribute

We can build an XML document using the following syntax

XElement xml = new XElement("Albums",
                        new XElement("Album",
                        new XAttribute("albumId", "2"),
                        new XElement("artistName", "Dave Matthews"),
                        new XElement("yearReleased", "2000")
                    ),
                    new XElement("Album",
                        new XAttribute("albumId", "3"),
                        new XElement("artistName", "John Mayer"),
                        new XElement("yearReleased", "2003")
                    )
                );
 
Console.WriteLine(xml);

 

Which in turn will produce:

 

<Albums>
  <Album albumId="2">
    <artistName>Dave Mathews</artistName>
    <yearReleased>2000</yearReleased>
  </Album>
  <Album albumId="3">
    <artistName>John Meyer</artistName>
    <yearReleased>2003</yearReleased>
  </Album>
</Albums>

 

Later we will dscuss how we can read and query against XML data.

Loading