簡體   English   中英

在C#中合並相同類型的xml節點

[英]Merge xml nodes of same type in C#

我有兩個相同類型的XML元素(來自具有相同模式的不同XML文檔),如下所示:

<Parent>
  <ChildType1>contentA</ChildType1>
  <ChildType2>contentB</ChildType2>
  <ChildType3>contentC</ChildType3>
</Parent>

<Parent>
  <ChildType1>contentD</ChildType1>
  <ChildType3>contentE</ChildType3>
</Parent>

元素類型ChildType1,ChildType2和ChildType3在Parent元素中最多只能有一個實例。

我需要做的是將第二個Parent節點的內容與第一個Parent節點合並到一個如下所示的新節點中:

<Parent>
  <ChildType1>contentD</ChildType1>
  <ChildType2>contentB</ChildType2>
  <ChildType3>contentE</ChildType3>
</Parent>

使用Linq to XML來解析源文檔。 然后在它們之間創建一個聯合,並按元素名稱分組,並根據您的需要使用組中的第一個/最后一個元素創建一個新文檔。

像這樣的東西:

var doc = XElement.Parse(@"
    <Parent>
        <ChildType1>contentA</ChildType1>
        <ChildType2>contentB</ChildType2>
        <ChildType3>contentC</ChildType3>
    </Parent>
");

 var doc2 = XElement.Parse(@"
    <Parent>
        <ChildType1>contentD</ChildType1>
        <ChildType3>contentE</ChildType3>
    </Parent>
");

var result = 
    from e in doc.Elements().Union(doc2.Elements())
    group e by e.Name into g
    select g.Last();
var merged = new XDocument(
    new XElement("root", result)
);

merged現在包含

<root>
    <ChildType1>contentD</ChildType1>
    <ChildType2>contentB</ChildType2>
    <ChildType3>contentE</ChildType3>
</root>

如果您將兩個初始文檔命名為xd0xd1那么這對我xd1

var nodes =
    from xe0 in xd0.Root.Elements()
    join xe1 in xd1.Root.Elements() on xe0.Name equals xe1.Name
    select new { xe0, xe1, };

foreach (var node in nodes)
{
    node.xe0.Value = node.xe1.Value;
}

我得到了這個結果:

<Parent>
  <ChildType1>contentD</ChildType1>
  <ChildType2>contentB</ChildType2>
  <ChildType3>contentE</ChildType3>
</Parent>

暫無
暫無

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

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