更新:November 2007
本主题说明如何获取属性的值。 主要方法有两种:可以将 XAttribute 强制转换为所需的类型;然后,显式转换运算符将元素或属性的内容转换为指定的类型。 此外,还可以使用 Value 属性。 但是,强制转换通常是更好的方法。 在检索可能存在也可能不存在的属性的值时,如果将属性强制转换为可以为 null 的类型,则代码会更易于编写。 有关此技术的示例,请参见如何:检索元素的值 (LINQ to XML)。
示例
若要检索属性的值,只需将 XAttribute 对象强制转换为所需的类型即可。
在 Visual Basic 中,可以使用集成的属性 (Attribute) 属性 (Property) 来检索属性 (Attribute) 的值。
XElement root = new XElement("Root",
new XAttribute("Attr", "abcde")
);
Console.WriteLine(root);
string str = (string)root.Attribute("Attr");
Console.WriteLine(str);
Dim root As XElement = <Root Attr="abcde"/>
Console.WriteLine(root)
Dim str As String = root.@Attr
Console.WriteLine(str)
本示例生成以下输出:
<Root Attr="abcde" />
abcde
在 Visual Basic 中,可以使用集成的属性 (Attribute) 属性 (Property) 来设置属性 (Attribute) 的值。 此外,如果使用集成的属性 (Attribute) 属性 (Property) 来设置不存在的属性 (Attribute) 的值,则会创建该属性 (Attribute)。
Dim root As XElement = <Root Att1="content"/>
root.@Att1 = "new content"
root.@Att2 = "new attribute"
Console.WriteLine(root)
本示例生成以下输出:
<Root Att1="new content" Att2="new attribute" />
下面的示例演示在属性处于命名空间中时,如何检索属性的值。 有关更多信息,请参见使用 XML 命名空间。
XNamespace aw = "https://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
new XAttribute(aw + "Attr", "abcde")
);
string str = (string)root.Attribute(aw + "Attr");
Console.WriteLine(str);
Imports <xmlns:aw="https://www.adventure-works.com">
Module Module1
Sub Main()
Dim root As XElement = <aw:Root aw:Attr="abcde"/>
Dim str As String = root.@aw:Attr
Console.WriteLine(str)
End Sub
End Module
本示例生成以下输出:
abcde