如何将所有 XML 文件转换为 XML 对象? [英] How to cast all XML files as XML objects?

查看:112
本文介绍了如何将所有 XML 文件转换为 XML 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can we use PowerShell to cast multiple XML files to objects?

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

Suppose we have a directory of XML files

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

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

我不知道如何继续 - 如果我们想在每个文件通过时查询它,我们是否需要嵌套的 foreach?

I am not sure how to proceed - if we want to query each file as it passes, do we need a nested foreach?

我只是转换为 XML 以在多个文档之间进行简单查询.我的所有文档都具有相同的架构,我想从每个文档中选择一组一致的节点和属性.

I am only casting as XML to make simple queries across multiple documents. All of my documents have identical schema and I want to select a consistent set of nodes and attributes from every document.

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

I have tried as suggested in the comments

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

推荐答案

如评论中所建议,您可以使用 Select-Xml cmdlet 直接针对文件运行 XPath 查询.

As suggested in the comments, you can use the Select-Xml cmdlet to run XPath queries directly against files.

您可以通过管道将 FileInfo 对象从 Get-ChildItem 直接传送到 Select-Xml:

You can pipe FileInfo objects from Get-ChildItem directly to Select-Xml:

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

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

If you need to use ForEach-Object or a loop to do further processing, supply the FullName property of the file to Select-Xml:

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

这篇关于如何将所有 XML 文件转换为 XML 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆