Consider that we want to create the following XML Document: 

<?xml version="1.0"? encoding="utf-8">
<!–Xml Document–>
<catalog>
   <book id="bk001">
      <title>Book Title</title>
   </book>
</catalog>

Here is how this XML document can be created using the classical DOM model through the System.Xml namespace:

XmlDocument xmlDoc = new XmlDocument();

XmlElement titleElement = xmlDoc.CreateElement("title");
titleElement.InnerText = "Book Title";

XmlElement bookElement = xmlDoc.CreateElement("book");
bookElement.SetAttribute("id", "bk001");
bookElement.AppendChild(titleElement);

XmlElement catalogElement = xmlDoc.CreateElement("catalog");
catalogElement.AppendChild(bookElement);

XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty);
XmlComment
xmlComment = xmlDoc.CreateComment("Xml Document");

xmlDoc.AppendChild(catalogElement);
xmlDoc.InsertBefore(xmlComment, catalogElement);
xmlDoc.InsertBefore(xmlDeclaration, xmlComment);

xmlDoc.Save("sample.xml");

When the classical DOM model is used, the task of creating a new document is made in an imperative way. This means that we have to instruct the API into doing what we want. The problem is that the API does not converge to the document structure, so we have to pay more attention to the API usage than to the real Xml structure.

Here is how we create the same XML document using Linq to Xml classes available in the System.Xml.XLinq namespace:

XDocument doc =
        new XDocument(
              new XDeclaration("1.0", Encoding.UTF8.HeaderName, String.Empty),
              new XComment("Xml Document"),
             
newXElement("catalog",
                    new XElement("book",
                          newXAttribute("id", "bk001"),
                                newXElement("title", "Book Title")
                    )
              )        
);

doc.Save("sampleLinq.xml");

As you can see, the Linq to Xml syntax is much more intuitive and directed towards the structure of the final document. This style of composing Xml document in Linq to Xml is known as Functional Construction.

 

Related posts:

  1. C# 3.0: Querying XML in C# with LINQ to XML LINQ to XML is a built-in LINQ data provider that...
  2. C# 3.0: Linq to Xml Object Model The Linq to Xml object model is very simple. The main...
  3. Here’s what you as a programmer need to know about LINQ How much do you know about LINQ? If you...
  4. Free Microsoft Press E-Book Offer: ‘Microsoft Visual C# 2008 Express Edition: Build a Program Now!’ Microsoft Press is now giving away “Microsoft Visual C#...