Friday 30 March 2012

Create XML Document using linq and with out using Linq....

The XML part

Now that we have an understanding of LINQ, it's time to move on to the XML part.
For this article, we will be using this XML file:


<?xml version="1.0" encoding="utf-8" ?>
<employees>
   <employee id="1" salaried="no">
      <name>Gustavo Achong</name>
      <hire_date>7/31/1996</hire_date>
   </employee>
   <employee id="3" salaried="yes">
      <name>Kim Abercrombie</name>
      <hire_date>12/12/1997</hire_date>
   </employee>
   <employee id="8" salaried="no">
      <name>Carla Adams</name>
      <hire_date>2/6/1998</hire_date>
   </employee>
   <employee id="9" salaried="yes">
      <name>Jay Adams</name>
      <hire_date>2/6/1998</hire_date>
   </employee>
</employees> 
 
 

The old way

In the previous versions of the .NET Framework, XML was document-centric; in other words, to create any structure, you first had to start with an XMLDocument.

The new way

Using the classes from the System.Xml.Linq namespace and the features available in .NET 3.5, constructing an XML document is very easy and very readable.
Constructing a document in this way is possible because of the functional construction feature in LINQ to XML. Functional construction is simply a means of creating an entire document tree in a single statement.
 
public XElement(XName name, Object[] content)
 
As we can see from one of the constructors for XElement, it takes an array of objects. In the example above, the employees element is constructed from four XElements, one for each employee, which in turn is constructed from XAttributes and other XElements.
In the above example, we could have replaced XDocument with XElement if we removed the XDeclaration and XComment objects. This is because the constructor XDocument used takes a XDeclaration instance, rather than the XName that the XElement constructor takes.


public XDocument(XDeclaration declaration,Object[] content) 
 
Another thing to note when running the demo is how both documents are printed to the console window.

As we can see, the old method just streams the contents of the document to the console. The method does that also; however, it is nicely formatted with no extra effort.

For Reference Visit..... 
 

No comments:

Post a Comment