簡體   English   中英

修改xml以將子節點合並到單個節點

[英]Modify xml to merge child nodes to a single node

我有XML作為服務的響應。

var Response = httpService.GetResponse();
XDocument doc = XDocument.Parse(Response);

xml看起來像這樣:

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <Parent>
    <ChildType1>contentA</ChildType1>
    <ChildType2>contentB</ChildType2>
    <ChildType3>contentC</ChildType3>
  </Parent>
  <Parent>
    <ChildType1>contentD</ChildType1>
    <ChildType3>contentE</ChildType3>
  </Parent>
</edmx:Edmx>

我該如何編輯它,使其看起來像這樣:

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <Parent>
    <ChildType1>contentA</ChildType1>
    <ChildType2>contentB</ChildType2>
    <ChildType3>contentC</ChildType3>
    <ChildType1>contentD</ChildType1>
    <ChildType3>contentE</ChildType3>
  </Parent>
</edmx:Edmx>

一旦您了解了如何使用XDocument,XElement,它就非常簡單。 我剛剛創建了一個List<XElement>來收集所有子元素,然后將它們附加到新的父元素並將父元素分配給根。

我強烈建議創建一個新文檔,而不是更新現有文檔。

解決方案1:詳細版本以了解其工作原理。

XDocument xDoc = XDocument.Parse(str);
List<XElement> allChildNodes = new List<XElement>();
foreach (var parent in xDoc.Root.Elements("Parent"))
{
    allChildNodes.AddRange(parent.Descendants());
}
XElement xParent = new XElement("Parent");
xParent.Add(allChildNodes);
xDoc.Root.Descendants().Remove();
xDoc.Root.Add(xParent);

解決方案2:感謝Jeff Mercado,我們提供了一個精簡版本。

XDocument xDoc = XDocument.Parse(str);
xDoc.Root.ReplaceNodes(
    new XElement("Parent", // New parent element is created
    xDoc.Root.Elements("Parent").Elements()));

輸出:

<root>
  <Parent>
    <ChildType1>contentA</ChildType1>
    <ChildType2>contentB</ChildType2>
    <ChildType3>contentC</ChildType3>
    <ChildType1>contentD</ChildType1>
    <ChildType3>contentE</ChildType3>
  </Parent>
</root>

要替換Parent節點,可以使用XElement.ReplaceNodes()替換根的子節點。 用包含替換節點的子節點的新Parent節點替換這些節點。

doc.Root.ReplaceNodes(
    new XElement("Parent",
        doc.Root.Elements("Parent").Elements()
    )
);

暫無
暫無

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

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