繁体   English   中英

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

[英]Merge multiple XML files into one using PowerShell 2.0?

我有一个非常大的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方法

干杯,Joakim

虽然XSLT的方法很短,但PowerShell的方式也是如此:

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

希望这可以帮助,

就个人而言,我不会将PowerShell用于此类任务。

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

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

那么你可以像对象一样使用xml。 很酷。 如果你需要处理大型xml结构,那么使用[xml] (相当于XmlDocument )非常耗费内存。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM