gpt4 book ai didi

Jsoup Element.wrap(String html) 方法抛出 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 11:41:49 25 4
gpt4 key购买 nike

我目前有代码将 Table 包裹在 Element 周围:

public static Element wrapElementInTable(Element e)
{
if (e == null)
return null;
return e.wrap(createTableTemplate().outerHtml());
}

public static Element createTableTemplate()
{
return createElement("table", "").appendChild(
createElement("tr").appendChild(
createElement("td"))
);
}

现在我在我的主要方法中创建一个元素:

public static void main(String[] args) throws IOException 
{
Element e = new Element(Tag.valueOf("span"),"");
String text = HtmlGenerator.wrapElementInTable(e).outerHtml();
System.out.println(text);
}

问题是我在 wrap 方法中收到一个 NullPointerException 显然没有任何原因。

Exception in thread "main" java.lang.NullPointerException
at org.jsoup.nodes.Node.wrap(Node.java:345)
at org.jsoup.nodes.Element.wrap(Element.java:444)
at usingjsoup.HtmlGenerator.wrapElementInTable(HtmlGenerator.java:56)
at usingjsoup.UsingJsoup.main(UsingJsoup.java:19)
Java Result: 1

有谁知道为什么会抛出 NullPointerException? (如果我在调用 wrap 之前打印出元素,输出就是我创建的标签)

最佳答案

我得到了答案,因为您没有父节点,所以抛出了 NPE。 Jsoup 尝试在不检查 parentNode 中的空值的情况下进行换行,如下所示

  //the below line throws NPE since parentNode is null
parentNode.replaceChild(this, wrap);

因此,您不能在没有parentNode 的情况下用input html String 包装Element。这样就可以做包裹了<p><div>与文档 (parentNode)

 public static void main(String[] args) throws IOException {
Document document = Jsoup.parse("<p>");
Element p = document.select("p").first();
Element div = document.createElement("div");
p.replaceWith(div);
div.appendChild(p);
System.out.println(document);
}

输出为

<html>
<head></head>
<body>
<div>
<p></p>
</div>
</body>
</html>

希望对你有帮助

关于Jsoup Element.wrap(String html) 方法抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com