如何创建按type属性值过滤的XPath,配合PowerShell Select-Xml提取XML数据
解决方案
你需要的属性过滤XPath写法和完整PowerShell实现如下:
核心逻辑说明
XPath中可以通过[@属性名='属性值']的语法过滤节点,搭配//前缀可以从文档任意层级开始匹配目标class节点,完全不需要硬编码节点索引,也不依赖instance的名称属性。
完整实现代码
# 定义你要过滤的class节点type属性值 $targetType = "I want to filter on whatever value this is" # 构造XPath:匹配所有type等于目标值的class节点下的全部instance节点 $xPath = "//class[@type='$targetType']/instance" # 输出表头 "QuestionSetName, Ratio" # 查询XML并格式化输出结果 Select-Xml -Path "你的XML文件完整路径.xml" -XPath $xPath | ForEach-Object { $currentInstance = $_.Node # 匹配当前instance下对应name的property取值 $questionSetName = ($currentInstance.property | Where-Object {$_.name -eq 'QuestionSetName'}).InnerText $ratio = ($currentInstance.property | Where-Object {$_.name -eq 'Ratio'}).InnerText # 输出拼接后的行 "$questionSetName, $ratio" }
输出结果
执行后会直接输出你需要的格式:
QuestionSetName, Ratio QuestionSet4, 5 QuestionSetTrust, 5
内容的提问来源于stack exchange,提问作者Christian Townsend
相关产品推荐
相关产品推荐

