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

Yoo*_*kim 6 xml powershell powershell-2.0

我有一个非常大的XML文件目录,结构如下:

file1.xml:

<root>
 <EmployeeInfo attr="one" />
 <EmployeeInfo attr="two" />
 <EmployeeInfo attr="three" />
</root>
Run Code Online (Sandbox Code Playgroud)

file2.xml:

<root>
 <EmployeeInfo attr="four" />
 <EmployeeInfo attr="five" />
 <EmployeeInfo attr="six" />
</root>
Run Code Online (Sandbox Code Playgroud)

现在我正在寻找一种将这些文件(*.xml)文件合并到一个输出文件中的简单方法:

<root>
 <EmployeeInfo attr="one" />
 <EmployeeInfo attr="two" />
 <EmployeeInfo attr="three" />
 <EmployeeInfo attr="four" />
 <EmployeeInfo attr="five" />
 <EmployeeInfo attr="six" />
</root>
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用像这样的纯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>
Run Code Online (Sandbox Code Playgroud)

这有效,但不如我想要的那么灵活.作为PowerShell(第2版)的新手,渴望学习在PowerShell中使用XML的新的最佳实践,我想知道什么是将XML文档结构合并为一个最简单,最纯粹的PowerShell方法

干杯,Joakim

Sta*_*ing 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")
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,

  • 如果*非常大的XML文件*非常大,那将消耗大量内存,并可能最终导致OutOfMemoryException. (2认同)