如何将所有XML文件转换为XML对象?

时间:2017-03-02 16:41:41

标签: xml powershell

我们如何使用PowerShell将多个XML文件转换为对象?

假设我们有一个XML文件目录

$xmlfiles = Get-ChildItem C:\Directory -Filter *.xml

foreach ($file in $xmlfiles) {
  [xml]$file Get-Content $_
}

我不确定如何继续 - 如果我们想要在传递时查询每个文件,我们是否需要嵌套foreach

我只是作为XML进行转换,以便跨多个文档进行简单查询。 我的所有文档都有相同的模式,我想从每个文档中选择一组一致的节点和属性。

我按照评论中的建议尝试了

foreach ($file in $xmlfiles) {
  Select-Xml $file -Xpath "//node2"
}

但是我得到了运行时异常:

Cannot convert value "sample-document.xml" to type "System.Xml.XmlDocument". Error:
"The specified node cannot be inserted as the valid child of this node, because the
specified node is the  wrong type."
At line:1 char:10
+ foreach ($file in $xmlfiles) {
+          ~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

1 个答案:

答案 0 :(得分:4)

根据评论中的建议,您可以使用the Select-Xml cmdlet直接针对文件运行XPath查询。

您可以将FileInfoGet-ChildItem对象直接传送到Select-Xml

Get-ChildItem C:\Directory -Filter *.xml |Select-Xml -XPath '//node2'

如果您需要使用ForEach-Object或循环进行进一步处理,请将文件的FullName属性提供给Select-Xml

foreach($xmlFile in Get-ChildItem C:\Directory -Filter *.xml){
    $QueryResult = Select-Xml -Path $xmlFile.FullName -XPath '//node2'
}
相关问题