6

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

文件 1.xml:

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

文件 2.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(第 2 版)的新手,渴望学习在 PowerShell 中使用 XML 的新最佳实践,我想知道将 XML 文档的结构合并为一个的最简单、最纯粹的PowerShell 方法是什么?

干杯,乔金

4

2 回答 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")

希望这可以帮助,

于 2010-06-04T15:22:11.017 回答
2

就我个人而言,我不会使用 PowerShell 来完成这样的任务。

通常你使用 PowerShell 来访问这样的配置文件

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

然后您可以像使用对象一样使用 xml。很酷。如果您需要处理大型 xml 结构,那么使用[xml](相当于XmlDocument)是相当昂贵的内存。

但是,这几乎就是 PowerShell 支持 xml 的所有方式(get-command *xml* -CommandType cmdlet将为您提供所有类似 xml 的命令)。
当然可以使用 .NET 类进行 xml 操作,但该代码不会像真正的 PowerShell 方法那样漂亮。因此,对于您的任务,您需要为此使用一些读者/作者,恕我直言不值得这样做。

这就是为什么我认为 xslt 是更好的方法;)如果您需要灵活,您可以在脚本执行期间生成 xlst 模板或只是替换文件名,这没问题。

于 2010-06-04T08:58:15.703 回答