简体   繁体   中英

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.

I have some XML that looks like this:

<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

<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?

I've included two from statements in a LINQ statement before, but not a second select , which seems to be what this would require.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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