Tuesday, June 5, 2012

XElement Example


The XElement class is used to a create XML elements, this class has methods to add/update/remove elements from XML fragments, the XElement class also contains methods to save the created XMLs into the File system.

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

XElement empXML =
 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")
    )
);
//
empXML.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 contents of the xml file Employees.xml will look as follows.
   
   <?xml version="1.0" encoding="utf-8" ?>
   <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>

The above example looks similar to the one which we saw using XDocument, but the XElement class cannot add comments and other header tags to the XML fragment, we will have to use the XDocument class if we need to add header details.


Search Flipkart Products:
Flipkart.com

No comments: