powershell - 使用 XPath 将 XML 转换为对象时出错
问题描述
我在 Powershell、XML 和 XPath 上苦苦挣扎。
我想要一个脚本来读取文件,提取我需要的节点并转换为我可以在脚本中使用的对象。
该文件如下所示:
<?xml version="1.0"?>
<Objs xmlns="http://schemas.microsoft.com/powershell/2004/04" Version="1.1.0.1">
<Obj RefId="0">
<TN RefId="0">
<T>System.Object</T>
</TN>
<Props>
<Obj N="Set1" RefId="1">
<TN RefId="1">
<T>System.Object</T>
</TN>
<Props>
<S N="Folder">C:\t1</S>
<Obj N="Configs" RefId="10">
<TN RefId="10">
<T>System.Object</T>
</TN>
<Props>
<S N="N1">Geralt</S>
<S N="N2">Ciri</S>
</Props>
</Obj>
</Props>
</Obj>
<Obj N="Set2" RefId="2">
<TN RefId="2">
<T>System.Object</T>
</TN>
<Props>
<S N="Folder">C:\t2</S>
<Obj N="Configs" RefId="20">
<TN RefId="20">
<T>System.Object</T>
</TN>
<Props>
<S N="N1">Triss</S>
<S N="N2">Yen</S>
</Props>
</Obj>
</Props>
</Obj>
</Props>
</Obj>
</Objs>
我写了这段代码:
$path = "c:\file.xml"
$xpath = "/ns:Objs/ns:Obj/ns:Props/ns:Obj[@N='Set2']"
$ns = "@{ns='http://schemas.microsoft.com/powershell/2004/04'}"
[xml]$apps = Select-Xml -Path $path -XPath $xpath -Namespace $ns
我期待能够写:
写入主机“文件夹是:$apps.Folder”-> C:\t1 写入主机“配置是:$apps.Configs.N2”-> 日元
但由于此错误,我无法获取对象:
Cannot convert value "...". Error: "This document already has a 'DocumentElement' node."
At line:1 char:1
+ [xml]$t = Select-Xml -Path $path -XPath "/ns:Objs/ns:Obj/ns:Props/ns:Obj[@N='Set2']"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
有什么建议么 ?
解决方案
这看起来像Export-CliXml
. 使用反序列化会更容易Import-CliXml
:
$apps = Import-Clixml -Path c:\file.xml
$apps.Set2.Folder
$apps.Set2.Configs.N2
在您的原始代码中,命名空间的语法错误。它应该是一个哈希表。
$ns = @{ns='http://schemas.microsoft.com/powershell/2004/04'}
用双引号将哈希表代码括起来会创建一个字符串。如果我们将您的 XPATH 表达式用于Obj
包含 的节点Set2
,您将需要进一步向下钻取节点树。
$path = "c:\file.xml"
$xpath = "/ns:Objs/ns:Obj/ns:Props/ns:Obj[@N='Set2']"
$ns = @{ns='http://schemas.microsoft.com/powershell/2004/04'}
$apps = Select-Xml -Path $path -XPath $xpath -Namespace $ns
$apps.Node.Props.S.Innertext # Folder value
$apps.Node.Props.Obj.Props.S.Innertext # Configs values
推荐阅读
- extjs - Extjs 经典网格面板滚动
- java - JPA:在 JPQL 中使用构造函数表达式在 DTO 中包装奇异实体时绕过 N+1
- laravel - 如何显示 laravel voyager 插入的产品图片?
- java - SMBJ 身份验证器支持哪个 NTLM 版本(1 或 2)?
- sql - postgres 函数未正确执行
- javascript - 错误的表情符号显示
- python - Python HTTP套接字:并不总是从发送JSON的客户端接收所有内容
- reactjs - 如何在函数 App() 父级和 Material-UI 嵌套侧边栏子级之间传递数据
- algorithm - 通过删除传递节点来减少图
- c# - 如何迁移实体框架中已经建立的一对多关系?