我试图通过给条件一个唯一值 U003_O100_001T_609644 来从几个 ViewItem 中找到带有值为 1900310 的谓词的 XPath 表达式。请看下面的代码,
我试着把表达式写成如下,
查询=/信封/正文/GetViewByIdResponse/GetViewByIdResult/Items/ViewItem/Fields/KeyValueOfstringanyType[Value='U003_O100_001T_609644']/Value[Key='ID']
但它并没有给我值(value)。你能帮忙吗?
谢谢最佳答案
一个选择所需元素的 XPath 表达式是:
/b:ViewItem
/b:Fields
/c:KeyValueOfstringanyType
[c:Key = 'ID']
/c:Value
请注意提供的 XML 文档具有命名空间,任何包含无前缀元素名称的 XPath 表达式都不会选择所需的元素,以下形式的表达式除外:
/*[local-name() = 'ViewItem']
/*[local-name() = 'Fields']
/*[local-name() = 'KeyValueOfstringanyType']
[*[local-name() = 'Key'] = 'ID']
/*[local-name() = 'Value']
此外,对于上面的第一个 XPath 表达式,命名空间以 "b:"
和 "c:"
为前缀
必须“注册”(阅读您的 XPath 引擎的文档,了解如何注册)。
基于 XSLT 的验证:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:b="some:b" xmlns:c="some:c">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select=
"/b:ViewItem
/b:Fields
/c:KeyValueOfstringanyType
[c:Key = 'ID']
/c:Value
"/>
==============
<xsl:copy-of select=
"/*[local-name() = 'ViewItem']
/*[local-name() = 'Fields']
/*[local-name() = 'KeyValueOfstringanyType']
[*[local-name() = 'Key'] = 'ID']
/*[local-name() = 'Value']
"/>
</xsl:template>
</xsl:stylesheet>
当此 XSLT 转换应用于以下 XML 文档时(提供的文档,已纠正严重的格式错误):
<b:ViewItem xmlns:b="some:b" xmlns:c="some:c">
<b:Fields>
<c:KeyValueOfstringanyType>
<c:Key>ID</c:Key>
<c:Value>1900310 </c:Value>
</c:KeyValueOfstringanyType>
<c:KeyValueOfstringanyType>
<c:Key>SubType</c:Key>
<c:Value>U003_O100_00IT_609644</c:Value>
</c:KeyValueOfstringanyType>
<c:KeyValueOfstringanyType>
<c:Key>SectionType</c:Key>
<c:Value>Released</c:Value>
</c:KeyValueOfstringanyType>
</b:Fields>
</b:ViewItem>
计算两个 XPath 表达式并输出它们选择的节点:
<c:Value xmlns:c="some:c" xmlns:b="some:b">1900310 </c:Value>
==============
<c:Value xmlns:c="some:c" xmlns:b="some:b">1900310 </c:Value>
关于xpath - 我正在尝试获取一个值的 Xpath 但嵌套条件出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9265480/