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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3719384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:09:28  来源:igfitidea点击:

Why can I not remove a child element I've just found? NOT_FOUND_ERR

javaxmlremovechildgetelementsbytagname

提问by dhardy

I'm building a script which has to patch XML files, including replacing one list of elements with another. The following function applies a patch (involving a possibly empty list of elements with the same name) onto a parent Element's list of elements by the same name (also possibly an empty list). (This is only a small part of the patching logic).

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

Why, when I run the code, do I get the following error?

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

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)

(Line 514 is labelled below.) As far as I understand it, I've just verified that the element exists (because NodeList is live, its first entry will always be the next match or null). Interestingly, this isn't always a problem.

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

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

Edit: I used the following function as a replacement for getElementsByTagName()(see accepted answer).

编辑:我使用以下函数代替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;
}

采纳答案by Maurice Perry

This is because when you are doing parent.removeChild(node), parent is not necessarily the parent of the node because getElementsByTagName() is doing a recursive search.

这是因为在执行 parent.removeChild(node) 时,parent 不一定是节点的父节点,因为 getElementsByTagName() 正在执行递归搜索。

回答by Kalpesh Soni

how about

怎么样

nodeToBeRemoved.getParentNode().removeChild(nodeToBeRemoved);

回答by dogbane

parent.removeChild(node)is throwing a NOT_FOUND_ERR because nodeis not a child of parent. I see that nodecomes from getElementsByTagNamewhich might not be an immediate child of parent. It could be anywhere under parent.

parent.removeChild(node)正在抛出 NOT_FOUND_ERR 因为node不是parent. 我看到node来自getElementsByTagName这可能不是一个立即的孩子parent。它可以在parent.

回答by LarsH

Building on the diagnosis by @Maurice and @fahd...

基于@Maurice 和@fahd 的诊断...

Can't you just put a condition before

你不能在前面加一个条件吗

parent.removeChild(node);

such as

if (parent.isSameNode(node.getParentNode()))

Then it would only remove a direct child of the given parent.

然后它只会删除给定父级的直接子级。