如何执行分层LINQ to XML查询?

时间:2011-11-15 20:46:03

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

我知道我可以迭代地执行此操作,但在单个LINQ语句中执行它会很酷。

我有一些看起来像这样的XML:

<parent name="george">
  <child name="steve" age="10" />
  <child name="sue" age="3" />
  <pet type="dog" />
  <child name="jill" age="7" />
</parent>
<!-- ... -->

我想写一个LINQ to XML语句把它变成

<node type="parent" label="george">
  <node type="child" label="steve" years="10 />
  <node type="child" label="sue" years="3" />
  <node type="child" label="jill" years="7" />
  <!-- no pets! -->
</parent>
<!-- ... -->

在单个LINQ to XML语句中可以实现吗?

我之前在LINQ语句中包含了两个from语句,但不是第二个select,这似乎是这需要的。

2 个答案:

答案 0 :(得分:3)

您需要查询所需的元素,并使用查询的项目创建新的元素和属性。这样的事情应该有效:

var input = @"<root>
    <parent name=""george"">
        <child name=""steve"" age=""10"" />
        <child name=""sue"" age=""3"" />
        <pet type=""dog"" />
        <child name=""jill"" age=""7"" />
    </parent>
</root>";

var xml = XElement.Parse(input);
var query = from p in xml.Elements("parent")
            select new XElement("node",
                new XAttribute("type", p.Name),
                new XAttribute("label", p.Attribute("name").Value),
                from c in p.Elements("child")
                select new XElement("node",
                    new XAttribute("type", c.Name),
                    new XAttribute("label", c.Attribute("name").Value),
                    new XAttribute("years", c.Attribute("age").Value)));

答案 1 :(得分:1)

又快又脏:

doc.Elements("parent")
            .Select(p =>
                new XElement("node",
                        new XAttribute("type", p.Name),
                        new XAttribute("label", p.Attribute("name") != null ? p.Attribute("name").Value : ""),
                        p.Elements("child")
                            .Select(c =>
                                    new XElement("node",
                                    new XAttribute("type", c.Name),
                                    new XAttribute("label", c.Attribute("name") != null ? c.Attribute("name").Value : ""),
                                    new XAttribute("years", c.Attribute("age") != null ? c.Attribute("age").Value : ""))
                                )
                        )
                );
相关问题