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:


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")

Which in turn will produce:

  <Album albumId="2">
    <artistName>Dave Mathews</artistName>
  <Album albumId="3">
    <artistName>John Meyer</artistName>

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

Leave a Reply

Your email address will not be published. Required fields are marked *