如何select 元素后面的文本?

How to select the text behind an element?

我有以下 xmllint 选择元素的示例:

$ curl -s http://lists.opencsw.org/pipermail/users/2015-January/date.html |
xmllint --html --xpath '/html/body/p/b[contains(., "Messages:")]' -
<b>Messages:</b>

粗体元素后面是我感兴趣的消息数。当我使用parent轴时显示:

$ curl -s http://lists.opencsw.org/pipermail/users/2015-January/date.html |
xmllint --html --xpath '/html/body/p/b[contains(., "Messages:")]/parent::*' -
<p><b>Starting:</b> <i>Thu Jan  1 23:17:09 CET 2015</i><br><b>Ending:</b> <i>Sat Jan 31 14:51:07 CET 2015</i><br><b>Messages:</b> 28</p>

我认为 following-sibling 轴可能会准确地给出这个数字,但事实并非如此:

$ curl -s http://lists.opencsw.org/pipermail/users/2015-January/date.html |
xmllint --html --xpath '/html/body/p/b[contains(., "Messages:")]/following-sibling::*' -
XPath set is empty

您要查找的这个文本节点确实是一个后续兄弟节点,但它是一个 text 节点,而不是元素节点。像

这样的表达式
following-sibling::*

仅查找以下 元素 的兄弟姐妹。要匹配文本节点,请使用 text():

$ curl -s http://lists.opencsw.org/pipermail/users/2015-January/date.html |
xmllint --html --xpath '/html/body/p/b[contains(., "Messages:")]/following-sibling::text()'

上面的命令在我的电脑上不起作用,在 Mac OS X 上使用 bash - 但我相信它对你有用。如果我先保存 curl 的结果然后使用

$ xmllint example.html --html --xpath '/html/body/p/b[contains(., "Messages:")]/following-sibling::text()'

结果是_28。这不是真正的下划线,而是我想指出的空白。要删除前导空格,请使用

$ xmllint example.html --html --xpath 'normalize-space(/html/body/p/b[contains(., "Messages:")]/following-sibling::text())'

不,使用正则表达式并不是一个真正的选择。