[英]c# linq xml attribute doesn't exist
我正在嘗試讀取xml文件並獲取屬性,但有時此屬性不存在。
如果不存在,則會出現此錯誤:
System.Linq.Enumerable + WhereSelectEnumerableIterator
2[System.Xml.Linq.XElement,<>f__AnonymousType0
2 [System.String,System.String]]
和:
嚴重錯誤:System.NullReferenceException:....
我的代碼:
string url = @"http://vigilance.meteofrance.com/data/NXFR33_LFPW_.xml";
XDocument doc = XDocument.Load(url);
var selectedBook = from r in doc.Descendants("DV")
.Where(r => (string)r.Attribute("dep").Value == Departement)
select new
{
Color = r.Attribute("coul").Value,
Risque = (string) r.Element("risque").Attribute("val").Value,
};
XML看起來像這樣:
<DV dep="02" coul="1"/>
<DV dep="03" coul="3">
<risque val="6"/>
</DV>
有人有主意嗎?
問題是某些DV
元素沒有子級risque
元素,因此在查詢的這一部分中:
Risque = (string) r.Element("risque").Attribute("val").Value
Element
將返回null
,並且在嘗試調用Attribute
時將獲得null引用異常。
您可以通過以下方法解決此問題:不從序列到最后一個項目,而要使用從元素和屬性到基本類型(如string
的顯式轉換。 這樣,從屬性轉換為null屬性的字符串將僅返回null。
Risque = (string) r.Elements("risque").Attributes("val").SingleOrDefault()
請參閱此小提琴以獲得有效的演示。
嘗試這個
XDocument doc = XDocument.Load(url);
var selectedBook = doc.Descendants("DV")
.Where(r => (string)r.Attribute("dep") == Departement)
.Select(r => new {
Color = r.Attribute("coul").Value,
Risque = r.Element("risque") == null ? null : (string)r.Element("risque").Attribute("val").Value,
}).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.