2011-03-13 34 views
0

我有這樣的XML:幫助與嵌套元素創建一個對象進行XML數據的

<stop> 
<code>2222222</code> 
<code_short>E2217</code_short> 
<name_fi>Konemies</name_fi> 
<name_sv>Maskinbyggaren</name_sv> 
<city_fi>Espoo</city_fi> 
<city_sv>Esbo</city_sv> 
<lines> 
    <node>2010 1:Puolarmetsä</node> 
    <node>2010K 1:Puolarmetsä</node> 
    <node>2052 2:Hämevaara</node> 
    <node>2103 1:Pohjois-Tapiola</node> 
    <node>2103T 1:Pohjois-Tapiola</node> 
    <node>2506 1:Pohjois-Tapiola</node> 
    <node>2512A 2:Malmin asema</node> 
    <node>2550 2:Itäkeskus, lait. 22</node> 
    <node>5510 2:Vantaankoski</node> 
</lines> </stop> 

我想是使用LINQ創建一個列表

其中一個車站:

public class Stop 
{ 
    public string code { get; set; } 
    public string shortCode { get; set; } 
    public string name { get; set; } 
    public string city { get; set; } 

    public IList<string> lines { get; set; } 

    public Stop() 
    { 
     lines = new List<string>(); 
    } 
} 

如何用LINQ實現這一目標?

這LINQ讓我停止

 XDocument xdoc = XDocument.Load("test.xml"); 

     var stop = (from node in xdoc.Element("response").Elements("node") 
        select new Stop 
        { 
         code = node.Element("code").Value, 
         shortCode = node.Element("code_short").Value, 
         name = node.Element("name").Value, 
         city = node.Element("city").Value 
        }); 

的列表,但我該如何處理線?想法?建議?

回答

2

像這樣:

XDocument xdoc = XDocument.Load("test.xml"); 

var stop = (from node in xdoc.Descendants("stop") 
      select new Stop 
      { 
       code = node.Attribute("code").Value, 
       shortCode = node.Attribute("code_short").Value, 
       name = node.Attribute("name").Value, 
       city = node.Attribute("city").Value, 
       lines = node.Element("lines") 
          .Elements("node") 
          .Select(x => (string) x) 
          .ToList() 
      }); 

上面的代碼還演示了轉換的XElement爲字符串的另一種方式 - 使用強制代替.Value屬性。如果XElement爲空,則轉換的結果將爲空,而.Value的結果將爲例外。如果元素缺失有效,則使用.Value是很好的,因爲一旦檢測到錯誤數據,它就會導致錯誤;對於「可選」元素,投射是容易遺漏值的簡單方法。

+0

錯誤姓名'x'在當前上下文中不存在 – 2011-03-13 08:55:50

+0

@digitalSurgeon:小錯字 - 現在已修復。 – 2011-03-13 08:56:43