Created
February 2, 2012 15:13
-
-
Save kardeiz/1723916 to your computer and use it in GitHub Desktop.
powershell script to combine multiple xml files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better to provide the details to enter what paths i should have