Mega Code Archive

 
Categories / C# Book / 05 LINQ XML
 

0539 XDocument

XDocument can accept only limited content: A single XElement object (the "root") A single XDeclaration object A single XDocumentType object (to reference a DTD) Any number of XProcessingInstruction objects Any number of XComment objects The simplest valid XDocument has just a root element: 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 XElement("test", "data")); Console.WriteLine(doc); } } The output: data The next example produces an XHTML file, illustrating all the constructs that an XDocument can accept: 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); } } The output: This is the content