Create and load XML documents using Linq

Code sample article
Table of Contents
Operations
Create XML document manually (initializing each item one by one)
How to do it
XElement xml =new XElement("contacts",
                    new XElement("contact",
                        new XAttribute("contactId", "1"),
                        new XElement("firstName", "João"),
                        new XElement("lastName", "Seixas"),
                            new XElement("addresses",
							    new XElement("address",
								    new XAttribute("type", "home"),
								    new XElement("street", "street 1"),
								    new XElement("city", "Funchal"),
								    new XElement("region", "Madeira"),
								    new XElement("zip", "9020-402")
							    ),
							    new XElement("address",
								    new XAttribute("type", "work"),
								    new XElement("street", "street 1 tecnopolo"),
								    new XElement("city", "Funchal"),
								    new XElement("region", "Madeira"),
								    new XElement("zip", "9020-420")
    							)
                            )
                        ),
                    new XElement("contact",
                        new XAttribute("contactId", "2"),
                        new XElement("firstName", "Ana"),
                        new XElement("lastName", "Travassos"),
						new XElement("addresses",
							new XElement("address",
								new XAttribute("type", "home"),
								new XElement("street", "street 2"),
								new XElement("city", "Funchal"),
								new XElement("region", "Madeira"),
								new XElement("zip", "9010-402")
							),
							new XElement("address",
								new XAttribute("type", "work"),
								new XElement("street", "street 2 tecnopolo"),
								new XElement("city", "Funchal"),
								new XElement("region", "Madeira"),
								new XElement("zip", "9010-420")
							)
						)
                    )
                );

Console.WriteLine(xml);
<contacts>
  <contact contactId="1">
    <firstName>João</firstName>
    <lastName>Seixas</lastName>
    <addresses>
      <address type="home">
        <street>street 1</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9020-402</zip>
      </address>
      <address type="work">
        <street>street 1 tecnopolo</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9020-420</zip>
      </address>
    </addresses>
  </contact>
  <contact contactId="2">
    <firstName>Ana</firstName>
    <lastName>Travassos</lastName>
    <addresses>
      <address type="home">
        <street>street 2</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9010-402</zip>
      </address>
      <address type="work">
        <street>street 2 tecnopolo</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9010-420</zip>
      </address>
    </addresses>
  </contact>
</contacts>
Create XML document manually with Xml Declaration, Comments and Namespaces (initializing each item one by one)
Remarks

The XmlDeclaration is only included in the generated XML only after saving to a file and then reading the file into memory.

How to do it
XNamespace ns = "urn:lst-cnt:cnt";

XDocument doc = new XDocument(
					new XDeclaration("1.0", "utf-8", "yes"),
					new XComment("This is a new comment"),
					new XElement(ns + "contacts",
						new XElement("contact",
							new XAttribute("contactId", "1"),
							new XElement("firstName", "João"),
							new XElement("lastName", "Seixas"),
							new XElement("addresses",
								new XElement("address",
									new XAttribute("type", "home"),
									new XElement("street", "street 1"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9020-402")
								),
								new XElement("address",
									new XAttribute("type", "work"),
									new XElement("street", "street 1 tecnopolo"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9020-420")
								)
							)
						),
						new XElement("contact",
							new XAttribute("contactId", "2"),
							new XElement("firstName", "Ana"),
							new XElement("lastName", "Travassos"),
							new XElement("addresses",
								new XElement("address",
									new XAttribute("type", "home"),
									new XElement("street", "street 2"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9010-402")
								),
								new XElement("address",
									new XAttribute("type", "work"),
									new XElement("street", "street 2 tecnopolo"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9010-420")
								)
							)
						)
					)
				);

doc.Save("Test.xml");
Console.WriteLine(File.ReadAllText("Test.xml"));
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--This is a new comment-->
<contacts xmls="urn:lst-cnt:cnt">
  <contact contactId="1">
    <firstName>João</firstName>
    <lastName>Seixas</lastName>
    <addresses>
      <address type="home">
        <street>street 1</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9020-402</zip>
      </address>
      <address type="work">
        <street>street 1 tecnopolo</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9020-420</zip>
      </address>
    </addresses>
  </contact>
  <contact contactId="2">
    <firstName>Ana</firstName>
    <lastName>Travassos</lastName>
    <addresses>
      <address type="home">
        <street>street 2</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9010-402</zip>
      </address>
      <address type="work">
        <street>street 2 tecnopolo</street>
        <city>Funchal</city>
        <region>Madeira</region>
        <zip>9010-420</zip>
      </address>
    </addresses>
  </contact>
</contacts>
Create XML document from relational database data or collections
How to do it
var lvCustomers = new[]
{
 new {CustomerID = 2, CustomerName = "Sumitra", Phone = "123-123-1236"},
 new {CustomerID = 3, CustomerName = "Wriju", Phone = "123-123-1235"},
 new {CustomerID = 4, CustomerName = "Writam", Phone = "123-123-1234"},
 new {CustomerID = 1, CustomerName = "Debajyoti", Phone = "123-123-1237"}
};

XElement xml = new XElement("customers",
                        from c in lvCustomers
                        orderby c.CustomerID
                        select new XElement("customer",
                            new XElement("name", c.CustomerName),
                            new XAttribute("ID", c.CustomerID),
                            new XElement("phone", c.Phone)
                                            )
                         );

Console.WriteLine(xml);
<customers>
  <customer ID="1">
    <name>Debajyoti</name>
    <phone>123-123-1237</phone>
  </customer>
  <customer ID="2">
    <name>Sumitra</name>
    <phone>123-123-1236</phone>
  </customer>
  <customer ID="3">
    <name>Wriju</name>
    <phone>123-123-1235</phone>
  </customer>
  <customer ID="4">
    <name>Writam</name>
    <phone>123-123-1234</phone>
  </customer>
</customers>
Load XML document
Remarks

The “XDocument” class contains a single root element: in this case “customers” obtained through the property “XDocument::Root()”. The child nodes are obtained through the method “XDocument::Root::Elements()”.

The “XElement” class contains a collections of elements – in the example above “customer” items – obtained through the method “XElement::Elements()”.

How to do it
// Load XML document from file (using XElement)...
XElement xml = Xelement.Load(@"\\PATH\file.xml");
// Load XML document text (using XElement)...
XElement xml = Xelement.Parse(@"<contact>...</contact>...<contact>...</contact>");

// Load XML document from file (using XDocument)...
XDocument xml = XDocument.Load(@"\\PATH\file.xml");
// Load XML document text (using XDocument)...
XDocument xml = XDocument.Parse(@"<contacts><contact>...</contact>...</contacts>");
Save the XML document to a XMLWriter or to the disk
How to do it
XNamespace ns = "urn:lst-cnt:cnt";

XDocument doc = new XDocument(
					new XDeclaration("1.0", "utf-8", "yes"),
					new XComment("This is a new comment"),
					new XElement(ns + "contacts",
						new XElement("contact",
							new XAttribute("contactId", "1"),
							new XElement("firstName", "João"),
							new XElement("lastName", "Seixas"),
							new XElement("addresses",
								new XElement("address",
									new XAttribute("type", "home"),
									new XElement("street", "street 1"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9020-402")
								),
								new XElement("address",
									new XAttribute("type", "work"),
									new XElement("street", "street 1 tecnopolo"),
									new XElement("city", "Funchal"),
									new XElement("region", "Madeira"),
									new XElement("zip", "9020-420")
								)
							)
						)
					)
				);

StringWriter sw = new StringWriter();
XmlWriter xwriter = XmlWriter.Create(sw);
doc.Save(xwriter);
xwriter.Close();

// save to disk
doc.Save("Test.xml");
Console.WriteLine(File.ReadAllText("Test.xml"));
Load the XML document using a XMLReader
How to do it
XmlReader xreader = XmlReader.Create("Test.xml");
XElement xelement = XElement.Load(xreader);
xreader.Close();
Print XDocument with ::ToString() method
Remarks

The XmlDeclaration is NOT included in the output text when the ::ToString() method is used. To overcome this limitation see the following code samples.

How to do it
string xml = @"<?xml version='1.0' encoding='utf-8'?>
                <Cooperations>
                   <Cooperation />
                </Cooperations>";

XDocument xdoc = XDocument.Parse(xml);

// Output XML document with XML declaraction (option 1)

Console.Write(String.Concat(xdoc.Declaration.ToString() , xdoc.ToString())

// Output XML document with XML declaraction (option 2)
// (Using string builder only encoding UTF-16 can be used)

StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
   doc.Save(writer);
}

Console.WriteLine(builder);

// Output XML document with XML declaraction (option 3)
// (Using memory stream any encoding can be used)

using(var mstream = new MemoryStream())
{
    using(var streamw = new StreamWriter(mstream, System.Text.UTF8Encoding.UTF8))
    {
         xdoc.Save(streamw);
         Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(mstream.ToArray()));
    }
}