2017-03-06 39 views
1

我有下面的語句C#列表XML中列出的LINQ

xdoc.Descendants("Father").Select(p => new 
    { 
     Son1 = (string)p.Element("Son1").Value, 
     Son2 = (string)p.Element("Son2").Value, 
     Son3= (string)p.Element("Son3").Value, 
     Son4 = (string)p.Element("Son4").Value, 
     Son5 = (string)p.Element("Son5").Value 

    }).ToList().ForEach(p => 
    { 

     Response.Write("Son1= " + p.Son1 + " "); 
     Response.Write("Son2=" + p.Son2 + " "); 
     Response.Write("Son3=" + p.Son3 + " "); 
     Response.Write(("Son4 =") + p.Son4 + " "); 
     Response.Write(("Son5 =") + p.Son5 + " "); 
     Response.Write("<br />"); 
    }); 

,它工作正常,只要我有每個兒子只有一個實例,問題是,我有Son5的多個實例,我鴕鳥政策知道如何把Son5內部列表

這裏是我的XML代碼示例:

enter image description here

回答

4

如果你有相同類型的多個元素,然後喲ü應解析它們列出或其他集合:

var fathers = from f in xdoc.Descendants("Father") 
       select new { 
       Son1 = (string)f.Element("Son1"), 
       Son2 = (string)f.Element("Son2"), 
       Son3= (string)f.Element("Son3"), 
       Son4 = (string)f.Element("Son4"), 
       Son5 = f.Elements("Son5").Select(s5 => (string)s5).ToList() 
      }; 

一些注意事項:

  • 不要使用XElementXAttribute.Value - 你可以施放元素本身對相應的數據類型,而無需訪問它的值。優點 - 更少的代碼,萬一元素更可靠的缺失(你不會得到的NullReferenceException)
  • 考慮使用intint?爲elemenent值,如果你的元素包含整數值
  • 如果你有一個Father元素,然後穿上」與收集父親工作。只需獲取xml root並檢查它是否爲空。之後,您可以創建單個father對象。

寫響應

foreach(var father in fathers) 
{ 
    Response.Write($"Son1={father.Son1} "); 
    Response.Write($"Son2={father.Son2} "); 
    Response.Write($"Son3={father.Son3} "); 
    Response.Write($"Son4={father.Son4} ");  
    Response.Write(String.Join(" ", father.Son5.Select(son5 => $"Son5={son5}"));  
    Response.Write("<br />"); 
} 
+1

謝謝你的提示 –

+0

@EvgenySdvizhkov還指出,通常你不應該直接寫字符串來響應。考慮爲您的操作創建視圖並使用剃鬚刀語法來顯示父數據 –

1

試試這個:

xdoc.Descendants("Father").Select(p => new 
{ 
    Son1 = p.Element("Son1").Value, 
    Son2 = p.Element("Son2").Value, 
    Son3= p.Element("Son3").Value, 
    Son4 = p.Element("Son4").Value, 
    Sons5 = p.Elements("Son5").Select(element => element.Value).ToList() 

}).ToList().ForEach(p => 
{ 

    Response.Write("Son1= " + p.Son1 + " "); 
    Response.Write("Son2=" + p.Son2 + " "); 
    Response.Write("Son3=" + p.Son3 + " "); 
    Response.Write("Son4 =" + p.Son4 + " "); 
    p.Sons5.ForEach(son5 => Response.Write("Son5 =" + son5 + " ")); 
    Response.Write("<br />"); 
}); 

這將你的項目,你可以在ForEach與另一ForEach迭代的列表中創建的Son5列表。

+0

將出現錯誤轉換列表(字符串) –

+0

@SergeyBerezovskiy:更正了該帖子。其實沒有一個演員是必要的 – Sefe

+0

這是非常有益的謝謝你 –