简体   繁体   English

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

[英]How to perform a hierarchical LINQ to XML query?

I know I can do this iteratively, but it would be cool to do it in a single LINQ statement. 我知道我可以迭代地执行此操作,但是在单个LINQ语句中执行此操作很酷。

I have some XML that looks like this: 我有一些看起来像这样的XML:

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

and I want to write a LINQ to XML statement to turn it into 我想编写一个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>
<!-- ... -->

Is that possible in a single LINQ to XML statement? 在单个LINQ to XML语句中有可能吗?

I've included two from statements in a LINQ statement before, but not a second select , which seems to be what this would require. 我之前在LINQ语句中包括了两个from语句,但是没有第二个select ,这似乎是需要的。

You'll need to query the desired elements and create new elements and attributes using the queried items. 您将需要查询所需的元素,并使用查询的项目创建新的元素和属性。 Something like this should work: 这样的事情应该起作用:

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)));

Quick and dirty: 快速又肮脏:

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 : ""))
                                )
                        )
                );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM