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