如何在PowerShell中通用查询XML的Restricted属性对应ID与Protection值
通用遍历XML查找指定属性节点的PowerShell实现
现有PowerShell代码仅能查询XML中ToolDgnPart节点里Protection属性为Restricted的条目,但实际需要实现通用逻辑——无需逐个指定节点(如ToolDgnPart、Rel、Form、View),遍历整个XML文档,找出所有Protection属性值为Restricted的节点,返回对应的id和Protection值。
原代码示例
$Xml = [xml]@' <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <TCXML xmlns="http://www.tcxml.org/Schemas/TCXMLSchema" format="low_level"> <ToolDgnPart Protection="Restricted" id="169487" creation_date="2022-06-03T15:10:14Z"/> <Rel elemId="id1414" id="42432"/> <Form Protection="Restricted" id="2347890" creation_date="2022-06-03T15:10:14Z"/> <View Protection="Restricted" id="2342345" creation_date="2022-06-03T15:10:14Z"/> </TCXML> '@ $xml.TCXML.ToolDgnPart | Where-Object Protection -eq 'Restricted' | ForEach-Object { [pscustomobject]@{ ID = $_.id Protection = $_.Protection } }
原代码返回结果
仅能匹配ToolDgnPart节点:
ID Protection -- ---------- 169487 Restricted
通用解决方案
利用XPath表达式结合XML命名空间处理,实现全文档节点匹配:
$Xml = [xml]@' <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <TCXML xmlns="http://www.tcxml.org/Schemas/TCXMLSchema" format="low_level"> <ToolDgnPart Protection="Restricted" id="169487" creation_date="2022-06-03T15:10:14Z"/> <Rel elemId="id1414" id="42432"/> <Form Protection="Restricted" id="2347890" creation_date="2022-06-03T15:10:14Z"/> <View Protection="Restricted" id="2342345" creation_date="2022-06-03T15:10:14Z"/> </TCXML> '@ # 绑定XML命名空间,避免XPath无法匹配节点 $nsManager = New-Object System.Xml.XmlNamespaceManager($Xml.NameTable) $nsManager.AddNamespace("tc", "http://www.tcxml.org/Schemas/TCXMLSchema") # 用XPath遍历所有符合条件的节点 $xml.SelectNodes("//tc:*[@Protection='Restricted']", $nsManager) | ForEach-Object { [pscustomobject]@{ ID = $_.id Protection = $_.Protection } }
代码说明
XmlNamespaceManager:处理XML默认命名空间,为命名空间绑定前缀tc,确保XPath能正确识别节点//tc:*[@Protection='Restricted']:XPath表达式逻辑//:遍历XML所有层级的节点tc:*:匹配所有属于tc命名空间的节点[@Protection='Restricted']:筛选出Protection属性值为Restricted的节点
修改后返回结果
匹配所有符合条件的节点:
ID Protection -- ---------- 169487 Restricted 2347890 Restricted 2342345 Restricted
内容的提问来源于stack exchange,提问作者Mice
相关产品推荐
相关产品推荐

