【问题标题】:Merge multiple XML files into one using PowerShell 2.0?使用 PowerShell 2.0 将多个 XML 文件合并为一个?
【发布时间】:2010-06-04 07:38:30
【问题描述】:

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

干杯, 乔金

【问题讨论】:

    标签: xml powershell powershell-2.0


    【解决方案1】:

    虽然执行此操作的 XSLT 方式很短,但 PowerShell 方式也是如此:

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

    希望这会有所帮助,

    【讨论】:

    • 如果 非常大的 XML 文件 真的很大,这将消耗大量内存并可能以 OutOfMemoryException 告终。
    • 谢谢,我会尽快解决这个问题!
    • 在你的例子中,第 4 行应该是 $finalXml += $xml.root.InnerXml 除了这个,就像一个魅力:)
    【解决方案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模板或者直接替换文件名,没问题。

    【讨论】:

      猜你喜欢
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2012-04-24
      • 2013-12-20
      相关资源
      最近更新 更多