屬性是與專案相關聯的名稱/值組。 類別 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 樹狀架構的開發人員而言很重要。 許多開發人員不會擔心這項區別。