XAttribute 類別概觀

屬性是與元素相關聯的成對名稱和數值。 XAttribute 類別表示 XML 屬性。

在 LINQ to XML 中使用屬性的方式類似於使用項目。 其建構函式類似。 您用來擷取其集合的方法也類似。 屬性集合的 LINQ 查詢運算式看起來非常類似元素集合的 LINQ 查詢運算式。

系統會保留將屬性加入到項目的順序。 也就是說,當您逐一查看屬性時,您會看到加入這些屬性的相同順序。

XAttribute 建構函式

下列 XAttribute 類別的建構函式就是您常用的建構函式:

建構函式 描述
XAttribute(XName name, object content) 建立 XAttribute 物件。 name 引數會指定屬性的名稱;content 會指定屬性的內容。

範例:建立具有屬性的元素

下列程式碼顯示建立包含屬性之元素的一般工作。

XElement phone = new XElement("Phone",
    new XAttribute("Type", "Home"),
    "555-555-5555");
Console.WriteLine(phone);
Dim phone As XElement = <Phone Type="Home">555-555-5555</Phone>
Console.WriteLine(phone)

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

<Phone Type="Home">555-555-5555</Phone>

範例:屬性的功能結構

您無法建構內嵌 XAttribute 物件之結構的 XElement 物件,如下所示:

XElement c = new XElement("Customers",
    new XElement("Customer",
        new XElement("Name", "John Doe"),
        new XElement("PhoneNumbers",
            new XElement("Phone",
                new XAttribute("type", "home"),
                "555-555-5555"),
            new XElement("Phone",
                new XAttribute("type", "work"),
                "666-666-6666")
        )
    )
);
Console.WriteLine(c);
Dim c As XElement = _
    <Customers>
        <Customer>
            <Name>John Doe</Name>
            <PhoneNumbers>
                <Phone type="home">555-555-5555</Phone>
                <Phone type="work">666-666-6666</Phone>
            </PhoneNumbers>
        </Customer>
    </Customers>
Console.WriteLine(c)

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

<Customers>
  <Customer>
    <Name>John Doe</Name>
    <PhoneNumbers>
      <Phone type="home">555-555-5555</Phone>
      <Phone type="work">666-666-6666</Phone>
    </PhoneNumbers>
  </Customer>
</Customers>

屬性不是節點

屬性和項目有一些差異。 XAttribute 物件在 XML 樹狀結構中不是節點。 它們是與 XML 元素相關聯的成對名稱和數值。 相較於文件物件模型 (DOM),這在反映 XML 的結構時,更為接近。 雖然 XAttribute 物件實際上在 XML 樹狀結構中不是節點,但是使用 XAttribute 物件的方式類似於使用 XElement 物件的方式。

這個區別只有對於撰寫可在節點層級使用 XML 樹狀結構之程式碼的開發人員特別重要。 這個區別與許多開發人員都無關。

另請參閱