函式建構 (LINQ to XML)

LINQ to XML 提供一種功能強大的方式來建立稱為「函式建構」的 XML 元素。 函式建構可讓您在單一陳述式中建立 XML 樹狀結構。

LINQ to XML 程式設計介面的數個主要功能可用於函式建構中:

  • XElement 建構函式會針對內容採用各種引數類型。 例如,您可以傳遞變成子項目的其他 XElement 物件。 您可以傳遞變成項目屬性的 XAttribute 物件。 或者,您可以傳遞轉換成字串的其他類物件型,然後變成項目的文字內容。
  • XElement 建構函式會採用 params 類型的 Object 陣列,讓您可以將任何數目的物件傳遞到建構函式。 這可讓您建立包含複雜內容的項目。
  • 如果物件實作 IEnumerable<T>,系統列舉物件中的集合,並加入集合中的所有項目。 如果集合包含 XElementXAttribute 物件,系統會個別加入集合中的每個項目。 這非常重要,因為這可讓您將 LINQ 查詢的結果傳遞到建構函式中。

範例:建立 XML 樹狀結構

您可以使用函式建構,撰寫程式碼來建立 XML 樹狀結構。 以下是一個範例:

XElement contacts =
    new XElement("Contacts",
        new XElement("Contact",
            new XElement("Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),
            new XElement("Address",
                new XElement("Street1", "123 Main St"),
                new XElement("City", "Mercer Island"),
                new XElement("State", "WA"),
                new XElement("Postal", "68042")
            )
        )
    );

範例:使用 LINQ 查詢結果建立 XML 樹狀結構

當您建立 XML 樹狀結構時,這些功能也可讓您撰寫程式碼來使用 LINQ 查詢結果,如下列範例所示:

XElement srcTree = new XElement("Root",
    new XElement("Element", 1),
    new XElement("Element", 2),
    new XElement("Element", 3),
    new XElement("Element", 4),
    new XElement("Element", 5)
);
XElement xmlTree = new XElement("Root",
    new XElement("Child", 1),
    new XElement("Child", 2),
    from el in srcTree.Elements()
    where (int)el > 2
    select el
);
Console.WriteLine(xmlTree);

在 Visual Basic 中,相同的作業也可透過 XML 常值達成:

Dim srcTree As XElement = _
    <Root>
        <Element>1</Element>
        <Element>2</Element>
        <Element>3</Element>
        <Element>4</Element>
        <Element>5</Element>
    </Root>
Dim xmlTree As XElement = _
    <Root>
        <Child>1</Child>
        <Child>2</Child>
        <%= From el In srcTree.Elements() _
            Where CInt(el) > 2 _
            Select el %>
    </Root>
Console.WriteLine(xmlTree)

這個範例會產生下列輸出:

<Root>
  <Child>1</Child>
  <Child>2</Child>
  <Element>3</Element>
  <Element>4</Element>
  <Element>5</Element>
</Root>

另請參閱