Wriju's BLOG

.NET, Cloud and everything

XLinq: Beginners Walkthrough

 


Let’s play with Linq to XML (aka XLinq). XLinq is different from conventional .NET way to work with XML. Linq to XML is not the replacement it is smarter and superior way to work with XML with Language-INtegrated Query.


 


Let’s suppose you need to create XML content like


 


<employees>


  <employee age=28>


    <name>Wriju</name>


    <email>wriju@abc.com</email>


  </employee>


  <employee age=18>


    <name>Writam</name>


    <email>writam@abc.com</email>


  </employee>


</employees>


 


using the power of XLinq. If you notice my code here you will find the name of objects under XLinq library start with “X” instead of Xml.


 


Here we go


 


XElement _xml = new XElement(“employees”,


                    new XElement(“employee”,


                        new XElement(“name”, “Wriju”),


                        new XAttribute(“age”, “28”),


                        new XElement(“email”, “wriju@abc.com”)


                ),


                    new XElement(“employee”,


                        new XElement(“name”, “Writam”),


                        new XAttribute(“age”, “18”),


                        new XElement(“email”, “writam@abc.com”)


                    )


                );


 


Console.WriteLine(_xml);


 


You can also save the content in proper XML format rather than just showing them in string.


 


_xml.Save(@”C:\MyXMLData.xml”);


 


Now this XML has couple of things missing like <?xml version=1.0 encoding=utf-8?>


 


To add this you need to create XDocument instead of XElement.


 


The code will look like


 


XDocument _doc = new XDocument(


    new XDeclaration(“1.0”, “utf-8”, “yes”),


    new XComment(“Sample XML”),


    new XElement(“employees”,


                    new XElement(“employee”,


                        new XElement(“name”, “Wriju”),


                        new XAttribute(“age”, “28”),


                        new XElement(“email”, “wriju@abc.com”)


                ),


                    new XElement(“employee”,


                        new XElement(“name”, “Writam”),


                        new XAttribute(“age”, “18”),


                        new XElement(“email”, “writam@abc.com”)


                    )


                )


);


 


To just display the data use


 


Console.WriteLine(_doc);


 


To save use,


_doc.Save(@”C:\MyXML.xml”);


 


Happy weekend!!!


 


Namoskar