Showing posts with label XDocument. Show all posts
Showing posts with label XDocument. Show all posts

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

LINQ to XML Classes Overview




LINQ to XML offers a dozen classes to create and parse XML’s, here we shall see some of the important classes.


All the LINQ to XML classes are packed in the System.Xml.Linq Assembly

XDocument: The XDocument class is used to add header information to the XML document, like declaration, version information, style details, etc, it also embeds the Xml elements, the XDocument class is not mandatory, can be used as and when required.
The XDocument class contains methods to load and save the XML files to the file system.

XElement: The XElement class is the main class which is used to create XML structures, it contains methods to create, update, delete XML Elements to an XML Structure.