2017-09-13 4 views
0

同じフォーマットでローカルマシンからいくつかのXMLファイルをループしようとしていますが、いくつかのファイルに要素が欠けています。ループが要素のないファイルに到達すると、select newでプログラムがクラッシュします。要素が存在するかどうかにかかわらずlinqを使ってxml要素をクエリする方法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() 
      }; 
関連する問題