我有一个方法,它的属性描述类型为“Element”,然后我尝试使用 Jsoup.after 方法添加另一个元素。
然而,它产生
线程“主”java.lang.IllegalArgumentException 中的异常:对象不能为空
。
另一方面,append 方法工作得很好,但这不是我真正想要的。
代码如下:
private static void buildTotalvaluesTable2()
{
Element readyDesc = new Element("p style=\"margin-top:5px\">This is description</p");
Element totalValuesTable = new Element("table style=\"width:100%; border: 0px; margin-top:20px;\" class=\"hidden\">" +
"<tbody></tbody>" +
"</table");
readyDesc.after(totalValuesTable.outerHtml());
System.out.println(readyDesc.outerHtml());
}
我真正想要实现的只是在 readyDesc 之后的 totalValuesTable。
有人可以帮忙吗?
最佳答案
让我们开始解释设置元素 b
是什么意思作为元素 a
的 sibling (这里用 a.after(b)
表示)。
简而言之就是放置元素b
<强>在parent
元素的元素 a
在 a
旁边(之后)的位置元素。
所以在这一点上我们可以看到您的代码的主要问题是它没有提供任何指向父元素的链接兄弟应该在其中放置。
简单的解决方案是
- 创建
Element
或Document
代表 parent , - 分配
a
元素作为父元素的子元素 - (仅在 1. 2. 之后)分配
b
元素作为a
的兄弟元素,
换句话说是这样的:
Element parent = new Element("body");
Element a = ...
parent.appendChild(first); // create parent-child relation
Element b = ...
a.after(b); // now `a` knows about its parent element so it knows
// to which element append `b`
第二个问题是你没有使用new Element(...)
正确地在
new Element("p style=\"margin-top:5px\">This is description</p");
该构造函数的目的不是创建和设置,而是创建 HTML 元素。自定义该元素应该稍后完成。
换句话说,不要使用 new Element("<tag with='attributes'>and other elements</tag>")
但是new Element("tagName")
并通过专用方法设置该元素,例如:
Element readyDesc = new Element("p");//use only name of tag, without < and >
System.out.println(readyDesc); //raw form: <p></p>
//customize tag
readyDesc.attr("style", "margin-top:5px");
readyDesc.text("This is description");
System.out.println(readyDesc);//customized: <p style="margin-top:5px">This is description</p>
关于java - 方法后的 Jsoup 无法按预期方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789638/