读取具有相同元素名称的xml

时间:2013-04-29 17:10:52

标签: c# linq xml-parsing

我的xml格式如下:

   <?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<draw><drawNo>381555</drawNo>
    <drawTime>2013-04-29T19:55:00+03:00</drawTime>
    <result>8</result>
    <result>10</result>
    <result>13</result>
    <result>15</result>
    <result>20</result>
    <result>21</result>
    <result>22</result>
    <result>25</result>
    <result>28</result>
    <result>29</result>
    <result>34</result>
    <result>36</result>
    <result>44</result>
    <result>46</result>
    <result>52</result>
    <result>62</result>
    <result>63</result>
    <result>72</result>
    <result>73</result>
    <result>75</result>
</draw>

我需要分割数据...... 我试过下面的代码:

XDocument loadeddata = XDocument.Parse(e.Result);
                var data = from query in loadeddata.Descendants("draw")
                           select new KinnoResults()
                                      {
                                          DrawNo = (String) query.Element("drawNo").Value,
                                          DrawTime = (String) query.Element("drawTime").Value,
                                          result1 = (String)query.Element("result").Value,
                                          result2 = (String)query.Element("result").Value

                                      };
                List<KinnoResults> list = data.ToList();

但是result1和result2有相同的值8。 好吗?

2 个答案:

答案 0 :(得分:1)

使用Elements,它会为您提供一个集合

   select new KinnoResults()
   {
       DrawNo = (String)query.Elements("drawNo").Value,
       DrawTime = (String)query.Element("drawTime").Value,
       result1 = (String)query.Elements("result").ToList()[0].Value,
       result2 = (String)query.Elements("result").ToList()[1].Value

   };

答案 1 :(得分:1)

var drawNo = loadeddata.Root.Element("drawNo").Value;
var drawTime = loadeddata.Root.Element("drawTime").Value;
var results = loadeddata.Descendants("result").Select(d => d.Value).ToList();