2017-09-13 79 views
0

我想從本地機器以相同的格式循環幾個XML文件,但一些文件有缺少的元素,這是圖像。當循環到達帶有缺失元素的文件時,程序在選擇新的時候崩潰。如何查詢xml元素使用linq是否存在該元素C#

XML:

<?xml version="1.0" encoding="UTF-8"?> 
<node> 
    <id>1663</vid> 

    <title>My Title</title> 

    <body> 
    <und keys="1"> 
     <n0> 
      <value>123 Street</value> 
      <summary></summary> 
      <format type="NULL"></format> 
      <safe_value>123 Street</safe_value> 
      <safe_summary></safe_summary> 
     </n0> 
    </und> 
    </body> 
    <field keys="1"></field> 
    <image> 
     <und keys="1"> 
      <i0>  
       <uri>https://uei.jpg</uri>  
      </i0> 
      <i1> 
       <uri>https://myurl.jpg</uri>  
      </i1> 
     </und> 
    </image> 
</node> 

LINQ的C#(WPF)APP:

XDocument document = XDocument.Load(file); 
var nodes = from b in document.Descendants("node") 
      let imgs = b.Element("image") 
      select new 
      { 
       ID = (string)b.Element("id").Value, 
       Title = (string)b.Element("title").Value, 
       StreetName = (string)b.Element("body").Element("und").Element("n0").Element("value").Value, 
       Images = imgs.Descendants("und").ToList() 
      }; 

回答

1

我想它墜毀因爲硬鑄件的?

嘗試使用保存鑄造和空條件操作這將防止NullreferenceExceptions(?):

XDocument document = XDocument.Load(file); 
var nodes = from b in document.Descendants("node") 
      let imgs = b.Element("image") 
      select new 
      { 
       ID = b.Element("id")?.Value as string, 
       Title = b.Element("title")?.Value as string, 
       StreetName = b.Element("body")?.Element("und")?.Element("n0")?.Element("value")?.Value as string, 
       Images = imgs?.Descendants("und")?.ToList() 
      };