如何用java删除XML节点

时间:2017-03-28 21:29:42

标签: java xml dom

我需要删除"对象"标签,但我需要保留并保留内容。那可能吗?

<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

我试过了:

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

但:

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

1 个答案:

答案 0 :(得分:1)

首先,只有要删除的节点的父节点才能将其删除:

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

其次,为了“保留和保留内容”,您需要将删除的子元素附加到其父元素:

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