使用 PowerShell 2.0 将多个 XML 文件合并为一个文件? [英] Merge multiple XML files into one using PowerShell 2.0?
问题描述
我有一个非常大的 XML 文件目录,其结构如下:
I have a directory of very large XML files with a structure as 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>
现在我正在寻找一种简单的方法将这些文件 (*.xml) 文件合并到一个输出文件中:
Now I am looking for a simple way to merge these files (*.xml) files into one output file:
<root>
<EmployeeInfo attr="one" />
<EmployeeInfo attr="two" />
<EmployeeInfo attr="three" />
<EmployeeInfo attr="four" />
<EmployeeInfo attr="five" />
<EmployeeInfo attr="six" />
</root>
我正在考虑使用像这样的纯 XSLT:
I was thinking about 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>
这可行,但没有我想要的那么灵活.作为 PowerShell(第 2 版)的新手,我渴望学习在 PowerShell 中使用 XML 的新最佳实践,我想知道将 XML 文档结构合并为一个的最简单、最纯粹的 PowerShell 方式是什么?
This works but isn't as flexible as I want. Being a novice with PowerShell (version 2) eager to learn new best pracctices of working with XML in PowerShell I am wondering what is the simplest, purest PowerShell way of merging the structre of XML documents into one?
干杯,乔金
推荐答案
虽然 XSLT 方法很短,但 PowerShell 方法也是如此:
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")
希望这会有所帮助,
这篇关于使用 PowerShell 2.0 将多个 XML 文件合并为一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!