Tuesday, June 5, 2012

XDocument Examples


The XDocument class is used to a embed the XML elements and other tags like comments, version information etc, the XDocument class also contains methods to save and load the XMLs into the File system.

The following example shows the usage of XDocument class in creating a XML fragment and saving it to the File system.

XDocument objXDoc = new XDocument(
    new XComment("Employee Details"),
    new XElement("Employees",
        new XElement("Employee",
            new XElement("Name",
                new XElement("FirstName", "Henry"),
                new XElement("LastName", "Ford")
            ),
            new XElement("Age","65")
        ),
         new XElement("Employee",
            new XElement("Name",
                new XElement("FirstName", "Bill"),
                new XElement("LastName", "Gates")
            ),
            new XElement("Age", "55")
        )
    )
);

objXDoc.Declaration = new XDeclaration("1.0", "utf-8", "true");
//
objXDoc.Save(@"D:\Employees.xml");


Once this code is executed the XML fragment is created and saved to the XML file Employees.xml in D:

The xml file Employees.xml look as follows.

   <?xml version="1.0" encoding="utf-8" ?>
   <!-- Employee Details  -->
   <Employees>
  <Employee>
<Name>
<FirstName>Henry</FirstName>
<LastName>Ford</LastName>
  </Name>
<Age>65</Age>
  </Employee>
  <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
  </Employee>
  </Employees>


As you could see, creating XML's using the XDocument class is much easier that using the conventional methods, earlier we had to create instances of the XMLNode class and keep adding them to the parent node to create the XML structure, now the work is much simple using the XDocument class.



Related Post

Search Flipkart Products:
Flipkart.com

No comments: