【问题标题】:Partial parse Comment tag in JSoupJSoup 中的部分解析 Comment 标签
【发布时间】:2015-09-13 00:11:08
【问题描述】:

我想检查 HTML 注释标签是否正确插入。如果有开始标签但没有结束标签,我想显示错误。

我引用了this link 并且能够检索到有效的评论节点

for(Element e : document.getAllElements()){
            for(Node n: e.childNodes()){
                if(n instanceof Comment){
                    commentNodes++;
                    System.out.println(n);
                }
            }
        }
        if(html.contains("<!--") && commentNodes == 0) {
            System.out.println("error");
        } else  if(html.contains("-->") && commentNodes == 0) {
            System.out.println("error1");
        }

有更好的方法吗?

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    我不确定 JSoup 是否会解析未关闭的评论标签,尽管还有另一种方法可以实现您的目标:

    int openings = StringUtils.countMatches(html, "<!--");
    int closures = StringUtils.countMatches(html, "-->");
    if (openings > closures)
        System.out.println("Error: There are not closed comment tags!");
    

    它将计算评论标签打开和关闭的出现次数,并通过比较它可以假设是否有未关闭的。为了完全确定结果,您还可以将这些值与 JSoup 获得的标签数量进行比较(在您的示例中为 commentNodes)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多