Merge multiple XML files into one using PowerShell 2.0?

蹲街弑〆低调 提交于 2019-12-04 05:32:21

While the XSLT way to do this is pretty short, so is the PowerShell way:

$finalXml = "<root>"
foreach ($file in $files) {
    [xml]$xml = Get-Content $file    
    $finalXml += $xml.InnerXml
}
$finalXml += "</root>"
([xml]$finalXml).Save("$pwd\final.xml")

Hope this helps,

Personally I would not use PowerShell for such a task.

Typically you use PowerShell to accessing config files like this

$config = [xml](gc web.config)

then you can work with the xml like with objects. Pretty cool. If you need to process large xml structures, then using [xml] (which is equivalent to XmlDocument) is quite memory expensive.

However, that's almost everything how PowerShell supports xml (get-command *xml* -CommandType cmdlet will give you all xml like commands).
It is of course possible to use .NET classes for xml operations, but that code won't be as pretty as true PowerShell approach. So, for your task you would need to use some readers/writers for that, which is imho not worthy doing.

That's why I think xslt is better approach ;) If you need to be flexible, you can generate the xlst template during script execution or just replace the file names, that's no problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!