该 XDocument 类包含有效 XML 文档所需的信息,其中包括 XML 声明、处理指令和注释。
仅当需要类提供XDocument的特定功能时,才需要创建XDocument对象。 在许多情况下,可以直接使用 XElement。 直接使用 XElement 是一个更简单的编程模型。
XDocument 派生自 XContainer,因此它可以包含子节点。 但是, XDocument 对象只能有一个子 XElement 节点。 这反映了 XML 标准,XML 文档中只能有一个根元素。
XDocument 的组件
XDocument 可以包含以下元素:
- 一个 XDeclaration 对象。 XDeclaration 使你能够指定 XML 声明的相关部分:XML 版本、文档的编码以及 XML 文档是否独立。
- 一个 XElement 对象。 此对象是 XML 文档的根节点。
- 任意数量的 XProcessingInstruction 对象。 处理指令将信息传达给处理 XML 的应用程序。
- 任意数量的 XComment 对象。 注释将与根元素同级。
- 一个用于 DTD 的 XDocumentType。
序列化XDocument时,即使XDocument.Declaration
为null
,如果编写器将Writer.Settings.OmitXmlDeclaration
设置为false
(默认),输出将包含XML声明。
默认情况下,LINQ to XML 将版本设置为“1.0”,并将编码设置为“utf-8”。
在没有 XDocument 的情况下使用 XElement
如前所述,该 XElement 类是 LINQ to XML 编程接口中的主类。 在许多情况下,应用程序不需要创建文档。 通过使用类 XElement ,可以:
- 创建 XML 树。
- 向其添加其他 XML 树。
- 修改 XML 树。
- 将其保存。
使用 XDocument
若要构造函数 XDocument,请使用函数构造,就像构造 XElement 对象一样。
以下示例创建一个 XDocument 对象及其关联的包含对象。
XDocument d = new XDocument(
new XComment("This is a comment."),
new XProcessingInstruction("xml-stylesheet",
"href='mystyle.css' title='Compact' type='text/css'"),
new XElement("Pubs",
new XElement("Book",
new XElement("Title", "Artifacts of Roman Civilization"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implements"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("This is another comment.")
);
d.Declaration = new XDeclaration("1.0", "utf-8", "true");
Console.WriteLine(d);
d.Save("test.xml");
Dim doc As XDocument = <?xml version="1.0" encoding="utf-8"?>
<!--This is a comment.-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs>
<Book>
<Title>Artifacts of Roman Civilization</Title>
<Author>Moreno, Jordao</Author>
</Book>
<Book>
<Title>Midieval Tools and Implements</Title>
<Author>Gazit, Inbar</Author>
</Book>
</Pubs>
<!--This is another comment.-->
doc.Save("test.xml")
此示例在 test.xml中生成此输出:
<?xml version="1.0" encoding="utf-8"?>
<!--This is a comment.-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs>
<Book>
<Title>Artifacts of Roman Civilization</Title>
<Author>Moreno, Jordao</Author>
</Book>
<Book>
<Title>Midieval Tools and Implements</Title>
<Author>Gazit, Inbar</Author>
</Book>
</Pubs>
<!--This is another comment.-->