Javascript Xpath查找匹配两个表达式的节点
我在下面的xml上使用xpath,我只需要提取匹配的节点 两个表达式,可能我做错了,因为没有返回节点Javascript Xpath查找匹配两个表达式的节点,javascript,xml,xpath,Javascript,Xml,Xpath,我在下面的xml上使用xpath,我只需要提取匹配的节点 两个表达式,可能我做错了,因为没有返回节点 <item> <title>a product</title> <link>http://www.aproduct.com</link> <description>cool product</description> <author>here@there.com<
<item>
<title>a product</title>
<link>http://www.aproduct.com</link>
<description>cool product</description>
<author>here@there.com</author>
<id_product><![CDATA[ 6]]></id_product>
<section><![CDATA[ industry]]></section>
</item>
<item>
<title>another product</title>
<link>http://www.anotherproduct.com</link>
<description>awesome product</description>
<author>here@there.com</author>
<id_product><![CDATA[ 8]]></id_product>
<section><![CDATA[ diy]]></section>
</item>
但我也试过了
//item/section[ . = "industry"] | //item/id_product[ . ="8"]
有人能帮我吗?您试图匹配的节点中的文本似乎以空格开头:
" industry"
" 8"
这就是为什么部分[text()=“industry”]
没有选择任何内容
你可以用
//item/section[normalize-space(.) = "industry"] | ...
p.S.根据您稍后的评论,您想要选择的内容似乎大不相同。您希望选择项
,而不是它的子项,并且您只需要两个条件均为true的项
元素,而不是两个条件均为true的元素。因此:
//item[section[normalize-space(.) = "industry"] and
id_product[normalize-space(.) = "6"]]
您可以使用XPath1.0函数
Xpath看起来像
//item/section[normalize-space(.) = "industry"]
|
//item/id_product[ normalize-space(.) ="6"]
更新:根据OP注释,我了解根据其子项持有的值选择的所有项目节点。那么这个表达式就可以了
//item[normalize-space(section) = "industry" or normalize-space(id_product) ="6"]
我正在尝试选择所有项目元素,其节子元素等于“industry”,id_产品子元素等于“6” 考虑到示例XML在元素值中有前导空格,在比较时需要使用
规范化空格
:
//item[normalize-space(section) = "industry"][normalize-space(id_product) = "6"]
序列中的多个谓词表达式被有效地AND组合在一起,您可以按如下方式读取表达式:
项目
元素行业的节子节点的节点
6
像
//item/section[..]
这样的表达式将选择节
元素,而不是它的父项
您要选择什么,项
元素节点或节
和id\u产品
节点?还要注意,在您的示例中,没有节
的内容等于“行业”-有一个节的内容为“行业”(带前导空格),我正在尝试选择节子级等于“行业”的所有项元素id_product child等于“6”感谢您的回答,我尝试使用strip space(.)但出现以下错误:NS_error_DOM_INVALID_EXPRESSION_ERR:表达式不是合法表达式。有什么想法吗?等等,现在它起作用了。。。不使用条带空间(.)。我添加了这样的空间://item/section[.=“industry”]我知道这很糟糕,但它很有效:)@Burn:my抱歉strip-space()
。我想到的是
,但正如其他人所指出的,删除初始和尾随空格的函数是normalize-space()
+1,这是一个有用的答案。然而,我认为OP希望谓词中有和,而不是或(如果我们可以从字面上理解他的评论的话)。
//item[normalize-space(section) = "industry"][normalize-space(id_product) = "6"]