Skip to content

Instantly share code, notes, and snippets.

@kardeiz
Created February 2, 2012 15:13
Show Gist options
  • Save kardeiz/1723916 to your computer and use it in GitHub Desktop.
Save kardeiz/1723916 to your computer and use it in GitHub Desktop.
powershell script to combine multiple xml files
# See best option below
# Option 1: Simple, but breaks with "xml" element
# based on an answer posted on stackoverflow by user "Start-Automating"
# see http://stackoverflow.com/questions/2972264/merge-multiple-xml-files-into-one-using-powershell-2-0
$files = get-childitem "full path to parent directory"
$finalXml = "<xml>"
foreach ($file in $files) {
[xml]$xml = Get-Content $file.fullname
$finalXml += $xml.xml.InnerXml
}
$finalXml += "</xml>"
$([xml]$finalXml).Save("full path to save location")
# Option 2
$xmldoc = new-object xml
$rootnode = $xmldoc.createelement("xml")
$xmldoc.appendchild($rootnode)
$dec = $xmldoc.CreateXmlDeclaration("1.0", $null, $null)
$xmldoc.InsertBefore($dec, $rootnode)
$files = gci "full path to parent directory"
foreach ($file in $files) {
$xmltoadd = select-xml -path $file.FullName -xpath "/*"
$xml2 = $xmltoadd.node.innerxml
$finalxml += $xml2
}
$rootnode.innerxml = $finalxml
$xmldoc.Save("full path to save location")
# Best option. Pretty prints XML
$xmldoc = new-object xml
$rootnode = $xmldoc.createelement("stuff")
$xmldoc.appendchild($rootnode)
$finalxml = $null
$files = gci "full path to directory"
foreach ($file in $files) {
[xml]$xmlstuff = gc $file.fullname
$innerel = $xmlstuff.selectnodes("/*/*")
foreach ($inone in $innerel) {
$inone = $xmldoc.importnode($inone, $true)
$rootnode.appendchild($inone)
}
}
# get rid of multiple spaces. might want to add regex to replace line breaks etc.
foreach ($t34 in $rootnode.selectnodes("//*/text()")) {
$t34.innertext = [regex]::replace($t34.innertext,"\s+"," ")
}
# create and set xmlwritersettings
$xws = new-object system.xml.XmlWriterSettings
$xws.Indent = $true
$xws.indentchars = "`t"
$xtw = [system.xml.XmlWriter]::create("full path to output", $xws)
$xmldoc.WriteContentTo($xtw)
$xtw.flush()
$xtw.dispose()
@narasimhakudva
Copy link

Better to provide the details to enter what paths i should have

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment