用于选择给定节点中的所有文本及其子节点的文本的 XPath 表达式 [英] XPath expression for selecting all text in a given node, and the text of its chldren

查看:25
本文介绍了用于选择给定节点中的所有文本及其子节点的文本的 XPath 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要抓取一些带有嵌套标签的文本.

像这样:

这是一个<span style="color:red">示例</span><b>粗体</b>文本

我想要一个能产生这个的表达式:

这是一个粗体文本示例

我为此苦苦挣扎了一个小时或更长时间,但没有结果.

感谢任何帮助

解决方案

string-元素节点的值是元素节点的所有文本节点后代的字符串值按文档顺序的串联.

您想在 div 元素上调用 XPath string() 函数.

string(//div[@id='theNode'])

您还可以使用 normalize-space 函数来减少由于源文档中的换行和缩进而可能出现的不需要的空白.这将删除前导和尾随空格,并用单个空格替换空格字符序列.当您将节点集传递给 normalize-space() 时,节点集将首先转换为它的字符串值.如果没有参数传递给 normalize-space,它将使用上下文节点.

normalize-space(//div[@id='theNode'])//如果 theNode 是上下文节点,您可以使用它来代替规范化空间()

您可能希望使用比我一直使用的示例 XPath 更有效的方式来选择上下文节点.例如,以下 Javascript 示例可以在某些浏览器中针对此页面运行.

var el = document.getElementById('问题');var result = document.evaluate('normalize-space()', el, null ).stringValue;

spanb 元素之间的纯空白文本节点可能有问题.

Basically I need to scrape some text that has nested tags.

Something like this:

<div id='theNode'>
This is an <span style="color:red">example</span> <b>bolded</b> text
</div>

And I want an expression that will produce this:

This is an example bolded text

I have been struggling with this for hour or more with no result.

Any help is appreciated

解决方案

The string-value of an element node is the concatenation of the string-values of all text node descendants of the element node in document order.

You want to call the XPath string() function on the div element.

string(//div[@id='theNode'])

You can also use the normalize-space function to reduce unwanted whitespace that might appear due to newlines and indenting in the source document. This will remove leading and trailing whitespace and replace sequences of whitespace characters with a single space. When you pass a nodeset to normalize-space(), the nodeset will first be converted to it's string-value. If no arguments are passed to normalize-space it will use the context node.

normalize-space(//div[@id='theNode'])

// if theNode was the context node, you could use this instead
normalize-space()

You might want use a more efficient way of selecting the context node than the example XPath I have been using. eg, the following Javascript example can be run against this page in some browsers.

var el = document.getElementById('question');
var result = document.evaluate('normalize-space()', el, null ).stringValue;

The whitespace only text node between the span and b elements might be a problem.

这篇关于用于选择给定节点中的所有文本及其子节点的文本的 XPath 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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