2010-11-19 140 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;