使用解析器更新 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)
更新:
是否有任何解析器可以以简单的方式更新文本节点中的文本
I always gets error in the middlebitparent.replaceWith(nodespan);
in the following code which is written in jsoup to navigate the HTML doc and change the background color of word "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);
The error says
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)
UPDATE:
Is there any parser which can update text in text node in an easy way
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试支持 XPath 的 HtmlCleaner,这对您的情况会更有用。 Jsoup的CSS选择器无法过滤文本节点。
You can try HtmlCleaner which support XPath which will be more useful in your case. Jsoup's CSS selector cannot filter the text node.