Tuesday, June 5, 2012

XAttribute Example


The XAttribute class is used along with the XElement class to append attributes to the XML Elements.

The following example shows the usage of XAttribute class to add attributes to the XML Elements

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("Department", new XAttribute("Name","Automobile"))
    ),
     new XElement("Employee",
        new XElement("Name",
            new XElement("FirstName", "Bill"),
            new XElement("LastName", "Gates")
        ),
        new XElement("Age", "55"),
        new XElement("Department", new XAttribute("Name","Software"))
    )
);
//
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>
<Department Name="Automobile" />
    </Employee>
    <Employee>
<Name>
<FirstName>Bill</FirstName>
<LastName>Gates</LastName>
</Name>
<Age>55</Age>
<Department Name="Software" />
   </Employee>

Search Flipkart Products:
Flipkart.com

No comments: