Archit Arora
Archit Arora

Reputation: 2626

remove parent node while preserving child node in jsoup

Consider this sample code-

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

I want to get the following output -

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

How do I achieve this? Thanks!

Upvotes: 7

Views: 2423

Answers (1)

ashatte
ashatte

Reputation: 5538

This solution will work for your current example:

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);
}

Result is:

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

Upvotes: 5

Related Questions