Groovy XmlSlurper with TagSoup 和不间断空格值



我正在使用 Groovy 的 XmlSlurper 解析一些 HTML4,并由标签汤Parser提供支持。

我成功地获得了节点的text(),但是 HTML  空间在尝试测试与另一个值的相等性时给我带来了一些困难。具体来说,.trim()实际上并没有修剪所有空格的字符串。 在我看来,值两侧的字符都是空格(请参阅下面的代码(,但String.trim()并没有按照我期望的方式修剪。 从代码示例中可以看出,字符串中第一个字符的Character.isSpaceChar()被确定为空格字符。

为什么String.trim()不修剪我从XmlSlurper获得的这个值?

@Grab('org.ccil.cowan.tagsoup:tagsoup:1.2.1')
import org.ccil.cowan.tagsoup.Parser
def html = '''
<html>
<body>
<span id="interested">&nbsp;hello&nbsp;</span>
</body>
</html>
'''
def slurper = new XmlSlurper(new Parser() )
def document = slurper.parseText(html)
def value = document.'**'.find { it['@id'] == 'interested' }.text()
println "value=[${value}]"
println "first char isWhitespace? ${Character.isWhitespace(value.charAt(0))}"
println "first char isSpaceChar? ${Character.isSpaceChar(value.charAt(0))}"
assert 'hello' == value.trim()

收益 率:

value=[ hello ]
first char isWhitespace? false
first char isSpaceChar? true
Exception thrown
Assertion failed: 
assert 'hello' == value.trim()
               |  |     |
               |  |      hello 
               |   hello 
               false

我正在使用Groovy Version: 2.3.6 JVM: 1.8.0 Vendor: Oracle Corporation OS: Mac OS X

在这里你已经纠正了例子:

@Grab('org.ccil.cowan.tagsoup:tagsoup:1.2.1')
import org.ccil.cowan.tagsoup.Parser
def html = '''
<html>
<body>
<span id="interested">&nbsp;hello&nbsp;</span>
</body>
</html>
'''
def slurper = new XmlSlurper(new Parser() )
def document = slurper.parseText(html)
def value = document.'**'.find { it['@id'] == 'interested' }.text()
println "value=[${value}]"
println "first char isWhitespace? ${Character.isWhitespace(value.charAt(0))}"
println "first char isSpaceChar? ${Character.isSpaceChar(value.charAt(0))}"
value = value.trim()
println "first char isWhitespace? ${Character.isWhitespace(value.charAt(0))}"
println "first char isSpaceChar? ${Character.isSpaceChar(value.charAt(0))}"
assert 'hello' == value.replaceAll(String.valueOf((char) 160), " ").trim()

解释可以在这里找到(空格与不间断空格(。

最新更新