Share via


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 对象。 注释将与根元素同级。
  • 一个用于 DTD 的 XDocumentType

序列化 XDocument 时,即使 XDocument.Declarationnull,输出也将具有 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.-->

另请参阅