共用方式為


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 的物件。 批註將會是根元素的同層級。
  • 一個 XDocumentType 用於 DTD。

當您串行化 XDocument時,即使 XDocument.Declarationnull,如果寫入器已 Writer.Settings.OmitXmlDeclaration 設定為 false ,輸出也會有 XML 宣告(預設值)。

根據預設,LINQ to XML 會將版本設定為 「1.0」,並將編碼設定為 「utf-8」。。

使用 XElement 而不使用 XDocument

如先前所述,類別 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.-->

另請參閱