属性是与元素关联的名称/值对。 类 XAttribute 表示 XML 属性。
在 LINQ to XML 中使用属性类似于使用元素。 它们的构造函数类似。 用来检索这些集合的方法很相似。 属性集合的 LINQ 查询表达式类似于元素集合的 LINQ 查询表达式。
将属性添加到元素的顺序将保留。 也就是说,当你遍历属性时,你会看到它们的顺序与添加时相同。
XAttribute 构造函数
以下是你最常使用的 XAttribute 类的构造函数:
构造函数 | DESCRIPTION |
---|---|
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 树的代码的开发人员。 许多开发人员不会担心这种区别。