我总是在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)
是否有任何解析器可以轻松更新文本节点中的文本
答案 0 :(得分: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选择器无法过滤文本节点。