XML节点未被正确删除

时间:2017-06-16 21:25:51

标签: java xml dom

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>myobj__c</members>
        <name>CustomObject</name>
    </types>
    <version>38.0</version>
</Package>

XML遵循上述结构。我需要删除节点的中间节点。即无论程序运行多少次,都应该删除。 我的尝试:

private static void removeNodes(Document document) {

    Node categories = document.getElementsByTagName("types").item(0);
    NodeList categorieslist = categories.getChildNodes();
    if(categorieslist != null) {
        while (categorieslist.getLength() > 1) {
            Node node = categorieslist.item(0);
            node.getParentNode().removeChild(node);
        }
    }
}

现在,如果我运行该程序一旦工作正常,但是当我运行它三次或更多时,结果是它也删除了节点,有时它删除节点的开始和结束标记,有时它会离开结束标签。 上面提到的问题提到categorieslist.getLength() > 1,但有时候它仍然失败。

尝试categorieslist.getLength() > 0,结果如下。

 <?xml version="1.0" encoding="UTF-8"?>
 <Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>38.0</version>
 </Package>

预期结果

 <?xml version="1.0" encoding="UTF-8"?>
 <Package xmlns="http://soap.sforce.com/2006/04/metadata">
     <types>
     </types>
    <version>38.0</version>
 </Package>

第二次尝试

private static void removeNodes(Document document) {

    DocumentTraversal traversal = (DocumentTraversal) document;
    Node a = document.getDocumentElement();
    NodeIterator iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
    Element b = null;
    for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
        Element e = (Element) n;
        b = e;
        if ("members".equals(e.getTagName())) {
            a.removeChild(b);
        }

        if ("name".equals(e.getTagName())) {
            a.removeChild(b);
        }
    }

投掷错误:org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist. at remove method.

请帮忙。

0 个答案:

没有答案