XDocument
In this chapter you will learn:
Get to know 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;/* ja v a 2 s.c om*/
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:
Create XML file with XDocument
The next example produces an XHTML
file,
illustrating all the constructs that an XDocument
can accept:
using System;/*from ja va 2 s.c om*/
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);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » XML Linq