gpt4 book ai didi

java - 如何用java删除XML节点

转载 作者:行者123 更新时间:2023-12-02 13:34:30 29 4
gpt4 key购买 nike

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

<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.

最佳答案

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

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

关于java - 如何用java删除XML节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43080300/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com