2010-11-19 208 views

回答

3

您应该使用XAttribute类的Value属性:

string attrValue = element.Attribute("name").Value; 

注意,Attributes()方法返回一个IEnumerable<XAttribute>,你必须遍历,而不是XAttribute实例。而且,那些是方法而不是索引属性:你需要使用圆括号而不是方括号来调用它们。

XAttribute也不支持InnerText属性,因此您必须改用Value

+0

什么区别?另外,属性[xxx]和属性(xxx)之间有什么区别? – user496949 2010-11-19 10:44:13

+0

@ user496949,没有区别,因为'XAttribute'不支持'InnerText'。看到我更新的答案。我使用LINQ To XML类型,因为你的问题被标记为这样,也许你想要别的东西? – 2010-11-19 10:52:02

1

您可以使用此选项,捕捉异常,如果属性为null

string attrValue = node.Attributes["name"] == null ? string.Empty : node.Attributes["name"].Value; 
相关问题