使用 xPath 和联合选择节点 [英] Selecting Nodes using xPath with unions

查看:26
本文介绍了使用 xPath 和联合选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基于使用 xPath 操作数据的基本 HTML 报告模板系统.本质上,我需要一个 xPath 查询,该查询将选择一个节点或其子节点(如果它们具有某个类).

I'm writing a basic HTML report templating system based on manipulating the data using xPath. Essentially, I need an xPath query which will select a node OR its children if they have a certain class.

$query = $xPath->query (".//*[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')]", $node);

我了解 xPath 选择器 .//*[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] 专门查看 $node 参数的 后代节点.

I understand that the xPath selector .//*[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] is specifically looking at descendant nodes of the $node parameter.

我想要一个本质上询问节点或其任何子节点"的 xPath 查询.我知道有一个联合运算符 |,但我还没有看到如何实现它.我会想象这样的事情: .[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] |.//*[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] 但这会生成一个无效表达式 错误.

I would like an xPath query that essentially asks "the node or any of its children". I know that there is a union operator, |, but I haven't seen how to implement that. I would have imagined something like this: .[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] | .//*[contains(concat(' ', normalize-space(@class), ' '), ' -delete-if-no-stock ')] but this generates an Invalid expression error.

推荐答案

Xpath 表达式用作过滤器.它们不是那种意义上的聚合/编译(就像 SQL 联合).

Xpath expressions work as filters. They do not aggregate/compile in that kind of sense (Like an SQL Union).

这里有几种可能性,具体取决于您要做什么.

Here are several possibilities depending on what you're trying to do.

管道符号 | 允许您指定多个表达式 - 它的作用类似于 CSS 选择器中的逗号 ,.

The pipe symbol | allows you to specify multiple expressions - it works like the comma , in CSS selectors.

expression_one|expression_two

表达式中的条件可以使用 andor 以及括号.

Conditions in the expressions can use and and or as well as brackets.

/location/path[条件和条件或条件]

Xpath 表达式有一个轴的概念,它定义了过滤器应用于的初始节点集.

Xpath expressions have a concept of axis that define the initial set of nodes the filter is applied to.

axis::node[condition]

.//*self::node()/descendant::* 的缩写.这是一个名为 descendant-or-self 的轴,它包括当前节点和所有后代.

.//* is short for self::node()/descendant::*. Here is a axis called descendant-or-self that includes the current node and all descendants.

后代或自我::*[contains(...)]

这篇关于使用 xPath 和联合选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆