Search code examples
c#xmllinq-to-xmlxelement

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>

Solution

  • 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>