使用解析器更新HTML页面中的文本



我总是在middlebitparent.replaceWith(nodespan);中出错在以下用jsoup编写的代码中,导航HTML文档并更改单词"in"的背景色

Elements divs= doc.select("div");
          for(Element div : divs)
          {
               if (div.hasText())
                {
                    int pos = div.text().indexOf("In");
                    out.println(pos);
                    if (pos >= 0)
                        {
                        Element span = doc.createElement("span");
                        span.attr("style", "background-color: yellow");
                        TextNode text = new TextNode(div.text(),"");
                      //  String[] words = div.split("\s", 4);
                     TextNode middlebit = text.splitText(4);
                     TextNode endbit=text.splitText("In".length());           
                      Node middleclone = middlebit.clone();
                      span.appendChild(middleclone);
                      Node nodespan=span.clone();
                      Node middlebitparent = middlebit.parent();
                      middlebitparent.replaceWith(nodespan);

错误显示

java.lang.NullPointerException
    org.apache.jsp.Page1_jsp._jspService(Page1_jsp.java:177)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

更新:

是否有任何解析器可以以简单的方式更新文本节点中的文本

    public static void main(String[] arg){
         HtmlCleaner cleaner = new HtmlCleaner();
         try {
             TagNode nodes = cleaner.clean(new File("c:/test.xml"));
             Object[] objects = nodes.evaluateXPath("//div/a[text(.,'In')]");
             System.out.println(((TagNode)objects[0]).getText());
         } catch (Exception e) {
            e.printStackTrace();
        }
    }

您可以尝试HtmlCleaner,它支持XPath,在您的情况下会更有用。Jsoup的CSS选择器无法筛选文本节点。

相关内容

  • 没有找到相关文章

最新更新