Merge multiple XML files into one using PowerShell 2.0?

I have a directory of very large XML files with a structure like this:

file1.xml:

<root> <EmployeeInfo attr="one" /> <EmployeeInfo attr="two" /> <EmployeeInfo attr="three" /> </root> 

file2.xml:

 <root> <EmployeeInfo attr="four" /> <EmployeeInfo attr="five" /> <EmployeeInfo attr="six" /> </root> 

Now I am looking for an easy way to combine the files of these files (* .xml) into one output file:

 <root> <EmployeeInfo attr="one" /> <EmployeeInfo attr="two" /> <EmployeeInfo attr="three" /> <EmployeeInfo attr="four" /> <EmployeeInfo attr="five" /> <EmployeeInfo attr="six" /> </root> 

I was thinking of using pure XSLT such as this one:

 <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <Container> <xsl:copy-of select="document('file1.xml')"/> <xsl:copy-of select="document('file2.xml')"/> </Container> </xsl:template> </xsl:stylesheet> 

It works, but not as flexible as I want. As a newbie to PowerShell (version 2), looking to learn new best practices for working with XML in PowerShell, I wonder what is the easiest and cleanest way for PowerShell to combine the structure of XML documents into one?

Cheers, Joachim

+6
xml powershell
source share
2 answers

Although the XSLT way of doing 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,

+11
source share

Personally, I would not use PowerShell for such a task.

You typically use PowerShell to access configuration files, such as

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

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

However, almost everything that supports PowerShell xml ( get-command *xml* -CommandType cmdlet will provide you with all the commands like xml).
Of course, you can use .NET classes for xml operations, but this code will not be as attractive as the real PowerShell approach. Thus, for your task, you will need to use some readers / writers for this, which imho does poorly.

That's why I think xslt is better;) If you need to be flexible, you can create an xlst template at runtime or just replace the file names, which is not a problem.

+2
source share

All Articles