gpt4 book ai didi

java - 为什么我不能删除刚找到的子元素? NOT_FOUND_ERR 错误

转载 作者:太空狗 更新时间:2023-10-29 22:38:47 26 4
gpt4 key购买 nike

我正在构建一个必须修补 XML 文件的脚本,包括将一个元素列表替换为另一个元素列表。以下函数将补丁(涉及可能为空的同名元素列表)应用到父元素的同名元素列表(也可能为空列表)。 (这只是补丁逻辑的一小部分)。

为什么,当我运行代码时,会出现以下错误?

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
at com.sun.org.apache.xerces.internal.dom.ParentNode.internalRemoveChild(ParentNode.java:503)
at com.sun.org.apache.xerces.internal.dom.ParentNode.removeChild(ParentNode.java:484)
at CombineSweeps$PTReplaceNodeList.apply(CombineSweeps.java:514)

(下面标记了第 514 行。)据我了解,我刚刚验证了该元素是否存在(因为 NodeList 是 Activity 的,它的第一个条目将始终是下一个匹配项或 null)。有趣的是,这并不总是一个问题。

private static class PTReplaceNodeList extends PTBase {
private final String name;
private final String nextElement;
private final List<Node> childList;

...

int apply(Document document, Node parent, Node node_unused) {
NodeList nodes;
// A marker for where to insert our nodes.
// We make a guess using nextElement (if null, means at end).
Node refNode = null;
if (parent instanceof Document) { // root element
Document parDoc = (Document) parent;
nodes = parDoc.getElementsByTagName(name);
if (nextElement != null) {
refNode = parDoc.getElementsByTagName(nextElement).item(0);
}
} else {
Element parElt = (Element) parent;
nodes = parElt.getElementsByTagName(name);
if (nextElement != null) {
refNode = parElt.getElementsByTagName(nextElement).item(0);
}
}

while (true) {
// iterate through the list of nodes
Node node = nodes.item(0);
if (node == null) {
break;
}

// Reliable guess: insert before node following last in list
refNode = node.getNextSibling();

parent.removeChild(node); // line 514
}

for (Node child : childList) {
Node imported = document.importNode(child, true);
parent.insertBefore(imported, refNode);
}
return childList.size();
}
}

编辑:我使用以下函数替代 getElementsByTagName()(参见接受的答案)。

/** Returns all direct children of node with name name.
*
* Note: not the same as getElementsByTagName(), which finds all descendants. */
static List<Node> getChildNodes( Node node, String name ){
ArrayList<Node> r = new ArrayList<Node>();
NodeList children = node.getChildNodes();
int l = children.getLength();
for( int i = 0; i < l; ++i ){
if( name.equals( children.item(i).getNodeName() ) )
r.add( children.item(i) );
}
return r;
}

最佳答案

怎么样

nodeToBeRemoved.getParentNode().removeChild(nodeToBeRemoved);

关于java - 为什么我不能删除刚找到的子元素? NOT_FOUND_ERR 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719384/

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