使用PowerShell 2.0将多个XML文件合并为一个?

6
我有一个非常大的XML文件目录,其结构如下:
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) 合并成一个输出文件:
<root>
 <EmployeeInfo attr="one" />
 <EmployeeInfo attr="two" />
 <EmployeeInfo attr="three" />
 <EmployeeInfo attr="four" />
 <EmployeeInfo attr="five" />
 <EmployeeInfo attr="six" />
</root>

我在考虑使用像这样的纯XSLT:
<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中使用XML的最佳实践的新手(版本2),我想知道将XML文档的结构合并为一个的最简单、最纯粹的PowerShell方式是什么?
祝好, Joakim
2个回答

11

虽然使用XSLT实现这个功能相对简短,但使用PowerShell也同样如此:

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

希望能有所帮助,


2
如果非常大的XML文件确实很大,那么它将消耗大量内存,并可能最终导致OutOfMemoryException。 - stej
谢谢,我会尝试这个作为快速修复! - Yooakim
1
在你的示例中,第4行应该是$finalXml += $xml.root.InnerXml除此之外,一切都运作得很好 :) - Vingt_centimes

2

个人认为不应该使用PowerShell来完成这样的任务。

通常情况下,您可以使用PowerShell来访问像这样的配置文件

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

然后,您可以像处理对象一样处理xml。非常酷。 如果需要处理大型xml结构,则使用[xml](相当于XmlDocument)会占用相当多的内存。
不过,这几乎是PowerShell支持xml的全部内容(get-command *xml* -CommandType cmdlet将为您提供所有类似xml的命令)。 当然,也可以使用.NET类进行xml操作,但该代码不如真正的PowerShell方法美观。因此,对于您的任务,您需要使用一些读取器/编写器,但我认为这并不值得做。
这就是我认为xslt更好的方法;) 如果需要灵活性,可以在脚本执行期间生成xslt模板或仅替换文件名,这没有问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接