3

I am trying to merge 2 XML files with common nodes using Powershell for example:

File1:

 <configuration>

      <SectionA>
         <section name="Name1" type="test1" />
      </SectionA>
      
      <SectionB>
       <add key="Key1" value="XYZ"/>
      </SectionB>

      <SectionC>
        <version="v1" abc="def"/>
      </SectionC>

    </configuration>

File2:

    <configuration>

  <SectionA>
     <section name="Name2" type="test2" />
  </SectionA>
  
  <SectionB>
   <add key="Key2" value="ABC"/>
  </SectionB>

  <SectionD>
    <version="v2" hij="klm"/>
  </SectionD>

</configuration>

I would like to combine these to have:

<configuration>

  <SectionA>
     <section name="Name1" type="test1" />
     <section name="Name2" type="test2" />
  </SectionA>
  
  <SectionB>
   <add key="Key1" value="XYZ"/>
   <add key="Key2" value="ABC"/>
  </SectionB>

  <SectionC>
    <version="v1" abc="def"/>
  </SectionC>
  
  <SectionD>
    <version="v2" hij="klm"/>
  </SectionD>

</configuration>

So far I have written up the code:

[xml]$File1 = Get-Content -Path File1.xml

[xml]$File2 = Get-Content -Path File1.xml

ForEach ($XmlNode in $File2.configuration.SectionA.ChildNodes) {
    $File1.configuration.SectionA.AppendChild($File1.ImportNode($XmlNode, $true))
}

ForEach ($XmlNode in $File2.configuration.SectionB.ChildNodes) {
    $File1.configuration.SectionB.AppendChild($File1.ImportNode($XmlNode, $true))
}


ForEach ($XmlNode in $File2.configuration.SectionD) {
    $File1.configuration.AppendChild($File1.ImportNode($XmlNode, $true))
}

$File1.Save('Combined.xml');
ii 'Combined.xml';

This works to an extent but I am wondering if there's generally a more efficient way of doing this without listing each individual section name or a way of just looping through the attributes as I will be using this for multiple different files with different contents.

Appreciate any help as I'm new to this :)

update: would be great if existing attributes would be overridden instead of duplicated. in the above code I've written it will just add duplicated if the key value pair exists in both files

user1
  • 86
  • 5

0 Answers0