java - 使用 Jsoup 在文档中插入元素

标签 java parsing jsoup

您好,我正在尝试在文档根元素中插入一个新的子元素,如下所示:

    Document doc = Jsoup.parse(doc);
    Elements els = doc.getElementsByTag("root");
    for (Element el : els) {
        Element j = el.appendElement("child");
    }

在上面的代码中,文档中只有一个根标签,因此基本上循环只会运行一次。

无论如何,该元素作为根元素“root”的最后一个元素被插入。

有什么方法可以插入一个子元素作为第一个元素吗?

示例:

<root>
 <!-- New Element must be inserted here -->
 <child></child>
 <child></chidl> 
 <!-- But it is inserted here at the bottom insted  -->
</root>

最佳答案

看看这是否对您有帮助:

    String html = "<root><child></child><child></chidl></root>";
    Document doc = Jsoup.parse(html);
    doc.selectFirst("root").child(0).before("<newChild></newChild>");
    System.out.println(doc.body().html());

输出:

<root>
 <newchild></newchild>
 <child></child>
 <child></child>
</root>

为了破译,它说:

  1. 选择第一个根元素
  2. 获取该根元素上的第一个子元素
  3. 在那个 child 之前插入这个元素

您可以使用child 方法中的任何索引来选择任何 child

示例:

    String html = "<root><child></child><child></chidl></root>";
    Document doc = Jsoup.parse(html);
    doc.selectFirst("root").child(1).before("<newChild></newChild>");
    System.out.println(doc.body().html());

输出:

<root>
 <child></child>
 <newchild></newchild>
 <child></child>
</root>

关于java - 使用 Jsoup 在文档中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942313/

相关文章:

java - 可选列表中的 AssertJ

java - JSP页面显示数据时出现java.lang.NumberFormatException

java - 验证 PDF 和 Excel 文件类型的模式

Java - 图片直到循环结束才显示?

c - XML解析编译错误

Java 如何将带重音符号的 "e"添加到字符串中?

java - 如何在线从不完整的网页(仅限 HTML)获取 HTML 表格内容?

java - JSOUP 仅删除关闭和/或打开 div

java - 解析特定类之前的某个标签的数据

parsing - 秒差距输入意外结束