遍历DOM树时Jsoup节点哈希码冲突

J F*_*ird 4 html java hash dom jsoup

我正在使用java jsoup来构建HTML DOM树,其中Node.hashCode()使用了它.但是我发现在遍历DOM树时有很多哈希码冲突,使用以下代码:

doc.traverse(new NodeVisitor(){

    @Override
    public void head(Node node, int depth) {

        System.out.println("node hash: "+ node.hashCode());

        /* some other operations */
    }

    @Override
    public void tail(Node node, int depth) {
        // TODO Auto-generated method stub

        /* some codes */
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当运行它时,即使在前几个输出中,我也会看到许多相同的哈希码.

哈希码非常大,我不期望这种奇怪的行为.我使用了jsoup-1.8.1.任何意见都将非常感谢,谢谢.

Jon*_*ica 5

注意:此错误已在jSoup 1.8.2中修复,因此我的答案不再适用.

它可能是jSoup源代码中的一个错误.从来源:

@Override
public int hashCode() {
   int result = parentNode != null ? parentNode.hashCode() : 0;
   // not children, or will block stack as they go back up to parent)
   result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
   return result;
}
Run Code Online (Sandbox Code Playgroud)

我不是Java专家,但如果它们具有相同的属性,它看起来可能会为不同的节点返回相同的值.(和同一位家长一样,感谢@alkis的评论)


编辑:我可以重现这个.使用以下HTML:

<html>
    <head>
    </head>
    <body>
        <div style="blah">TODO: write content</div>
        <div style="blah">Nothing here</div>
        <p style="test">Empty</p>
        <p style="nothing">Empty</p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

以下代码:

String html = //HTML posted above

Document doc = Jsoup.parse(html);

Elements elements = doc.select("[style]");
for (Element e : elements) {
   System.out.println(e.hashCode());
}
Run Code Online (Sandbox Code Playgroud)

它给:

-148184373
-148184373
-1050420242
2013043377
Run Code Online (Sandbox Code Playgroud)

在计算哈希时,它似乎完全忽略了内容文本,只有属性很重要.


您应该实现自己的解决方法.


这里报告 Bug .

  • 感谢您的报道,我已经解决了这个问题.它将在jsoup 1.8.2中 (2认同)