Mega Code Archive

 
Categories / C# Book / 05 LINQ XML
 

0540 XDocument Root

XDocument has a Root property that serves as a shortcut for accessing a document's single XElement. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static void Main() { var styleInstruction = new XProcessingInstruction("xml-stylesheet", "href='styles.css' type='text/css'"); var docType = new XDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", null); XNamespace ns = "http://www.w3.org/1999/xhtml"; var root = new XElement(ns + "html", new XElement(ns + "head", new XElement(ns + "title", "An XHTML page")), new XElement(ns + "body", new XElement(ns + "p", "This is the content")) ); var doc = new XDocument( new XDeclaration("1.0", "utf-8", "no"), new XComment("Reference a stylesheet"), styleInstruction, docType, root); doc.Save("test.html"); Console.WriteLine(doc.Root.Name.LocalName); // html XElement bodyNode = doc.Root.Element(ns + "body"); Console.WriteLine(bodyNode.Document == doc); // True } } The output: html True XDeclaration's constructor accepts three arguments, which correspond to the attributes version, encoding, and standalone. In the following example, test.xml is encoded in UTF-16: using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static void Main() { var doc = new XDocument( new XDeclaration("1.0", "utf-16", "yes"), new XElement("test", "data") ); doc.Save("test.xml"); Console.WriteLine(doc); } } The output: data