2

tagsoup にXmlSlurper裏打ちされたGroovy を使用して 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

4

1 に答える 1

3

ここで例を修正しました:

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

説明はここにあります(スペースと非改行スペース)。

于 2014-10-22T13:57:04.707 に答える