使用 jsoup 就地修改和替换标签内容

Modify & replace tag content in place using jsoup

我有这个字符串

String source = "<code> <b>code1</b></code><code><i>code2</i></code>";

我想要这个输出

String source = "<code> <b>code123</b></code><code><i>code256</i></code>";

我能够获取里面的所有文本 code

Elements code = doc.select("code");

for (Element c : code) {
    System.out.println(c.text());
}

但无法就地修改文本。我该怎么做

很简单:

myElement.text("my text here");

你的情况:

Elements code = doc.select("code");
for(Element c:code) {

    //will print the text which the Element currently has
    System.out.println(c.text());

    //will set the text
    c.text("<b>code123</b><i>code256</i>");
}

如您所见,text() 方法可用于获取文本,但 可用于设置文本。