XDocument 类概述

本主题介绍 XDocument 类。

XDocument 类概述

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 对象。 注释将与根元素同级。 XComment 对象不能是列表中的第一个参数,因为 XML 文档以注释开头无效。

  • 一个用于 DTD 的 XDocumentType

序列化 XDocument 时,即使 XDocument.Declaration 为 null,输出也将具有 XML 声明,前提是编写器已经将 Writer.Settings.OmitXmlDeclaration 设置为 false(默认值)。

默认情况下,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.-->

请参见

概念

LINQ to XML 编程概述