简体   繁体   中英

Merge xml nodes of same type in C#

I have 2 XML elements(from different XML documents with the same schema) of the same type looking like this:

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

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

Element types ChildType1, ChildType2 and ChildType3 can have at most one instance in the Parent element.

What I need to do is merge the content of the second Parent node with the first Parent node into a new node that would look like this:

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

Use Linq to XML to parse the source documents. Then create a union between them and group by element name and create a new document using the first/last elements in the groups depending on what you want.

Something like this:

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 now contains

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

If you name the two initial documents as xd0 and xd1 then this worked for me:

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

I got this result:

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

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