-1

我总是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)

更新:

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

4

1 回答 1

0
    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();
        }
    }

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

于 2011-07-02T08:02:54.013 回答