簡體   English   中英

如何執行分層LINQ to XML查詢?

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

我知道我可以迭代地執行此操作,但是在單個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 ,這似乎是需要的。

您將需要查詢所需的元素,並使用查詢的項目創建新的元素和屬性。 這樣的事情應該起作用:

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

快速又骯臟:

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