XDocument 類別概觀

XDocument 類別包含有效 XML 文件所需的資訊,其中包含 XML 宣告、處理指示和註解。

如果您需要 XDocument 類別所提供的特定功能,您僅需要建立 XDocument 物件。 在許多情況下,您可以直接使用 XElement。 直接使用 XElement 是較簡單的程式設計模型。

XDocument 衍伸自 XContainer,因此可包含子節點。 不過,XDocument 物件可以有只有一個 XElement 子節點。 這會反映 XML 標準,也就是說 XML 文件中只能有一個根項目 (Root Element)。

XDocument 的元件

XDocument 可以包含下列項目:

  • 一個 XDeclaration 物件。 XDeclaration 可讓您指定 XML 宣告的關聯部分:XML 版本、文件的編碼,以及 XML 文件是否是獨立的。
  • 一個 XElement 物件。 此物件是 XML 文件的根節點。
  • 任何數目的 XProcessingInstruction 物件。 處理指示會將資訊傳達到處理 XML 的應用程式。
  • 任何數目的 XComment 物件。 這些註解將是根項目的同層級。
  • 一個適用於 DTD 的 XDocumentType

當您序列化 XDocument 時,即使 XDocument.Declarationnull,如果寫入器已將 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.-->

另請參閱