Pages

Monday, September 2, 2013

Create XML through LINQ - C#


1. Firstly, Add namespace to use "XElement " class: 

 using System.Xml.Linq;


2. Call this Method to get the xml in string "
getXML" :

 public void MethodToWriteXml()
    {     

XElement contacts =
    new XElement("Contacts",
        new XElement("Contact",
            new XElement("Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144", 
                new XAttribute("Type", "Home")),
            new XElement("phone", "425-555-0145",
                new XAttribute("Type", "Work")),
            new XElement("Address",
                new XElement("Street1", "123 Main St"),
                new XElement("City", "Mercer Island"),
                new XElement("State", "WA"),
                new XElement("Postal", "68042")
            )
        )
    );
        string getXML = contacts.ToString();
    }




Output: (get output in string 'getXML')

<Contacts>
  <Contact>
    <Name>Patrick Hines</Name>
    <Phone Type="Home">206-555-0144</Phone>
    <phone Type="Work">425-555-0145</phone>
    <Address>
      <Street1>123 Main St</Street1>
      <City>Mercer Island</City>
      <State>WA</State>
      <Postal>68042</Postal>
    </Address>
  </Contact>
</Contacts>

No comments:

Post a Comment