XDocument到对象列表

时间:2013-02-26 21:02:50

标签: c# .net xml linq-to-xml

XDocument的内容是下面的XML。

我想获得一个List(),请参阅此消息的末尾。

<myXml>
  <myDatas code="01">
    <myVar name="myvar" value="A" />
    <myData name="A" value="A1" />
    <myData name="B" value="B1" />
  </myDatas>
  <myDatas code="02">
    <myVar name="myvar" value="B" />
    <myData name="A" value="A2" />
    <myData name="D" value="D2" />
  </myDatas>
</myXml>

public class MyData
{
    public string MainCode { get; set; }
    public string Code { get; set; }
    public string Value { get; set; }
}

我想要一个List(),这个内容应该是这样的:

new MyData { MainCode = "01"; Code = "A"; Value = "A1" };
new MyData { MainCode = "01"; Code = "B"; Value = "B1" };
new MyData { MainCode = "02"; Code = "A"; Value = "A2" };
new MyData { MainCode = "02"; Code = "D"; Value = "D2" };

1 个答案:

答案 0 :(得分:6)

当然 - 所以你需要这样的东西:

var query = from datas in doc.Root.Elements("myDatas")
            let code = (string) datas.Attribute("code")
            from data in datas.Elements("myData")
            select new MyData {
                MainCode = code,
                Code = (string) data.Attribute("name"),
                Value = (string) data.Attribute("value"),
            };

var list = query.ToList();

请注意多个from子句以展平结果。

另一种选择是找到所有“leaf”元素并从父级中获取代码部分:

var query = from data in doc.Descendants("myData")
            select new MyData {
                MainCode = (string) data.Parent.Attribute("code"),
                Code = (string) data.Attribute("name"),
                Value = (string) data.Attribute("value"),
            };

var list = query.ToList();

编辑:如果您的文档使用名称空间,那也很容易:

XNamespace ns = "http://the-uri-of-the-namespace";
var query = from data in doc.Descendants(ns + "myData")
            ...

这使用XName operator +(XNamespace, string)重载运算符。