gpt4 book ai didi

java - 为什么给定的代码抛出异常(Jsoup)

转载 作者:行者123 更新时间:2023-11-29 03:35:20 24 4
gpt4 key购买 nike

正如很多论坛上所说的那样,元素是 DOM 中节点的特例。

但是我遇到了一个违反这条规则的异常(exception)。

它在语句 elem.remove() 处抛出异常。

这里,ele 是一个元素。 remove() 是 Jsoup API 中的一个函数,用于从 DOM 中删除节点及其后代。

异常:-

[WARNING] 
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalArgumentException: Object must not be null
at org.jsoup.helper.Validate.notNull(Validate.java:16)
at org.jsoup.nodes.Node.remove(Node.java:266)
at XXX.YYY.ZZZ.Template_Matching.Template_Matching.removeProductLister(Template_Matching.java:80)
at XXX.YYY.ZZZ.Template_Matching.Template_Matching.main(Template_Matching.java:376)
... 6 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

代码:-

public static void function(Document doc1, Document doc2, String tag) {

//Checking for ULs
Elements uls_1 = doc1.getElementsByTag(tag);
Elements uls_2 = doc2.getElementsByTag(tag);

for (Element elem1 : uls_1) {

// Check if elem1 exists in DOM, If No, then continue

for (Element elem2 : uls_2) {

// Check if elem2 exists in DOM, If No, then continue

// If id matches, remove them
if ((!"".equals(elem1.id())) && (elem1.id().equals(elem2.id()))) {
elem1.remove();
elem2.remove();
break;
}
}
}
}

最佳答案

当一个人试图删除一个父元素已经被删除的元素时,就会发生错误。这可能指向 Jsoup 中的错误。移除父项不会同时移除子项吗?

解决方法是首先检查父级是否存在:

if (element != null && element.parent() != null) { // fixes java.lang.IllegalArgumentException in org.jsoup.helper.Validate.notNull
element.remove();
}

关于java - 为什么给定的代码抛出异常(Jsoup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879307/

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