Tiago Costa
Tiago Costa

Reputation: 1016

how remove XML Node with java

i need to remove the "Object" tag, but I need to preserve and keep the content. Is that possible?

<ds:KeyInfo>
    <wsse:SecurityTokenReference>
        <wsse:Reference URI="#b3f74c53-b79f-4dec-aa26-ca552f8f8745"/>
    </wsse:SecurityTokenReference>
</ds:KeyInfo>
<ds:Object Id="id1"> // <-Remove this
    <wsu:Timestamp>
        <wsu:Created>2017-03-28T20:21:44Z</wsu:Created>
        <wsu:Expires>2017-03-28T23:08:24Z</wsu:Expires>
    </wsu:Timestamp>
 </ds:Object>  // <-Remove this

I tried:

Node node = xml.getElementById("id1");
xml.getDocumentElement().removeChild(node);

but:

Org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.

Upvotes: 0

Views: 104

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

First of all, only the parent of the node to be removed can remove it:

Node nodeToBeRemoved = xmlDoc.getElementById("id1");
Node parentNode = nodeToBeRemoved.getParentNode();
Node removedNode = parentNode.removeChild(nodeToBeRemoved);

Second, in order to "preserve and keep the content" you will need to attach the children elements of the removed one to its parent:

NodeList removedChildren = removedNode.getChildNodes();
for (int i = 0 ; i < removedChildren.getLength(); i++) {
    Node child = removedChildren.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
        parentNode.appendChild(child);
    }
}

Upvotes: 1

Related Questions