在jsoup中保留子节点的同时删除父节点

remove parent node while preserving child node in jsoup

考虑这个示例代码-

<div>
<outer-tag> Some Text <inner-tag> Some more text</inner-tag></outer-tag>
</div>

我想获得以下输出 -

<div>
<inner-tag> Some more text</inner-tag>
</div>

如何实现?谢谢!

此解决方案适用于您当前的示例:

String html = "<div>"
                + "<outer-tag> Some Text <inner-tag> Some more text</inner-tag></outer-tag>"
                + "</div>";     

Document doc = Jsoup.parseBodyFragment(html);

for (Element _div : doc.select("div")) {

    // get the unwanted outer-tag
    Element outerTag = _div.select("outer-tag").first();

    // delete any TextNodes that are within outer-tag
    for (Node child : outerTag.childNodes()) {
        if (child instanceof TextNode) child.remove();
    }

    // unwrap to remove outer-tag and move inner-tag to child of parent div
    outerTag.unwrap();

    // print the result 
    System.out.println(_div);
}

结果是:

<div>
 <inner-tag>
    Some more text
 </inner-tag>
</div>