2016-07-18 31 views
0

我想讀取一個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> 

有沒有人有一個想法?

回答

0

的問題是,一些DV元素沒有一個孩子risque元素,所以在查詢中的這一部分:

Risque = (string) r.Element("risque").Attribute("val").Value 

Element將返回null,和當您嘗試撥打Attribute時,您將收到空引用異常。

您可以通過不從序列到單個項目直到結束,並使用從元素和屬性到原始類型(如string)的顯式轉換來解決此問題。這樣,從屬性轉換爲字符串的空屬性將只返回null。

Risque = (string) r.Elements("risque").Attributes("val").SingleOrDefault() 

查看this fiddle進行工作演示。

+0

非常感謝!你知道如何處理多個Risque節點嗎?例如 Hydro

+0

@Hydro這取決於您*想要處理的方式它。你想要第一個嗎?持續?最高?最低?總?他們全部的清單? –

+0

在這種情況下,使用'r.Elements(「risque」)。Attributes(「val」)。Select(x => x.Value).ToList()'的所有風險值列表 – Hydro

0

試試這個

  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(); 
+0

非常感謝! – Hydro