簡體   English   中英

如何在LINQ to XML語句中返回同級XElement?

[英]How to return sibling XElements in a LINQ to XML statement?

從以下XML輸入:

<root>
  <node name="one" value="1"/>
  <node name="two" value="2"/>
  <node name="three" value="3"/>
  <node name="four" value="4"/>
</root>";

我需要使用LINQ to XML來產生以下內容:

<root>
  <name content="one"/>
  <value content="1"/>
  <name content="two"/>
  <value content="2"/>
  <name content="three"/>
  <value content="3"/>
  <name content="four"/>
  <value content="4"/>
</root>

此代碼生成名稱元素,但不生成元素。

var input = @"
<root>
  <node name=""one"" value=""1""/>
  <node name=""two"" value=""2""/>
  <node name=""three"" value=""3""/>
  <node name=""four"" value=""4""/>
</root>";


var xml = XElement.Parse(input);
var query = new XElement("root",
    from p in xml.Elements("node")
    select new XElement("name",
        new XAttribute("content", p.Attribute("name").Value) /*,

        new XElement("value", new XAttribute("content", p.Attribute("value").Value)) */
        )
    );

如果我在最后一個圓括號內包括 XElement(在上面注釋),則它是name元素的子級,但是在右圓括號之外,它不再可以訪問q (它在查詢之外)。

感覺我需要將兩個XElement連接在一起,或者以某種方式將它們包含在另一個不產生任何XML的集合中。

您可以使用Enumerable.SelectMany方法展平屬性。 在查詢格式中,這等效於兩個from子句

var query = new XElement("root",
    from p in xml.Elements("node")
    from a in p.Attributes()
    select new XElement(a.Name,
        new XAttribute("content", a.Value)
        )
    );

相比之下,使用實際的SelectMany方法並流暢地編寫它看起來像這樣:

var query = new XElement("root",
        xml.Elements("node")
           .SelectMany(n => n.Attributes())
           .Select(a => new XElement(a.Name,
                new XAttribute("content", a.Value))));

但是,我傾向於發現大多數SelectMany用法中的查詢語法都更清晰,並且我傾向於堅持一種或另一種格式,盡管將兩種格式混合使用都很好。

以您的代碼為起點。 將對包裹在item元素中,然后將其替換為其子項。

        var xml = XElement.Parse(input);
        var result = new XElement("root",
            from p in xml.Elements("node")
            select new XElement("item", 
                        new XElement("name", new XAttribute("content", p.Attribute("name").Value)),
                        new XElement("value", new XAttribute("content", p.Attribute("value").Value))));

        result.Descendants("item").ToList().ForEach(n => n.ReplaceWith(n.Elements()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM