XDocument Root

In this chapter you will learn:

  1. How to access XDocument Root

Access XDocument Root

XDocument has a Root property that serves as a shortcut for accessing a document's single XElement.

using System;//from j  a  va 2  s.com
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", "", "", 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:

Next chapter...

What you will learn in the next chapter:

  1. Query an XML document with Linq
Home » C# Tutorial » XML Linq
XDocument
Create XDocument
Add to XDocument
Parse XML file with XDocument
Load XML string with XDocument
XDocument Root
Query XML document with Linq
Save XML document
XDocument Serialize
XElement namespace
Adding attribute
XElement's NextNode
XAttribute
XAttribute value
XAttribute Properties
XAttribute namespace
XComment
XDeclaration
XML declaration
XCData
XNamespace