2
是类似于node.Attributes [“name”]。InnerText的好方法?如何从节点获取属性xml
是类似于node.Attributes [“name”]。InnerText的好方法?如何从节点获取属性xml
您应该使用XAttribute类的Value属性:
string attrValue = element.Attribute("name").Value;
注意,Attributes()方法返回一个IEnumerable<XAttribute>
,你必须遍历,而不是XAttribute
实例。而且,那些是方法而不是索引属性:你需要使用圆括号而不是方括号来调用它们。
XAttribute
也不支持InnerText
属性,因此您必须改用Value
。
您可以使用此选项,捕捉异常,如果属性为null
string attrValue = node.Attributes["name"] == null ? string.Empty : node.Attributes["name"].Value;
什么区别?另外,属性[xxx]和属性(xxx)之间有什么区别? – user496949 2010-11-19 10:44:13
@ user496949,没有区别,因为'XAttribute'不支持'InnerText'。看到我更新的答案。我使用LINQ To XML类型,因为你的问题被标记为这样,也许你想要别的东西? – 2010-11-19 10:52:02