我想讀取一個xml文件並獲取屬性,但有時此屬性不存在。c#linq 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>
有沒有人有一個想法?
非常感謝!你知道如何處理多個Risque節點嗎?例如 –
Hydro
@Hydro這取決於您*想要處理的方式它。你想要第一個嗎?持續?最高?最低?總?他們全部的清單? –
在這種情況下,使用'r.Elements(「risque」)。Attributes(「val」)。Select(x => x.Value).ToList()'的所有風險值列表 – Hydro