带有TagSoup的Groovy XmlSlurper和不间断的空间值

时间:2014-10-22 13:51:44

标签: java string groovy xmlslurper tag-soup

我正在使用由标记句XmlSlurper支持的Groovy Parser解析一些HTML4。

我成功地获得了节点的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

1 个答案:

答案 0 :(得分:2)

此处您已更正示例:

@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()

可以找到解释here(空间与不间断空间)。