Wriju's BLOG

.NET, Cloud and everything

LINQ to XML : Creating complete XML document

LINQ to XML API allows us to create complete XML document as expected with all the elements. So this X-DOM has everything as you expect.


Simple sample looks like,



XDocument doc = new XDocument(

    new XDeclaration(“1.0”, “utf-16”, “true”),

    new XProcessingInstruction(“test”, “value”),

    new XComment(“This is comment by you”),

    new XElement(“Employees”,

        new XElement(“Employee”,

            new XAttribute(“id”, “EMP001”),

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

            new XCData(“~~~~~~~XML CDATA~~~~~~~~”))));


By calling Save method of XDocument (actually of XContainer) you can save it to a physical file. And the file will look like,


<?xml version=1.0 encoding=utf-16 ?>

<?test value?>

  <!– This is comment by you –>


  <Employee id=EMP001>


    <![CDATA[ ~~~~~~~XML CDATA~~~~~~~~]]>




To me this looks like more aligned to the human thinking mechanism.