简体   繁体   English

使用java中的Document删除xml中的节点

[英]Removing a node in xml using Document in java

I'am using org.w3c.dom.Document for xml parsing.I have a xml file in my server like.. 我正在使用org.w3c.dom.Document进行xml解析。我的服务器中有一个xml文件,比如..

<query><item access='server1'><item access='server2'><item access='server3'></query>

I will read this xml file and based on some option's i will remove any of the node(server1 or server2 or server3) dynamically and return the result as a string so that i can show in one of my user interface.below is the code 我将读取此xml文件,并根据某些选项,我将动态删除任何节点(server1或server2或server3)并将结果作为字符串返回,以便我可以在我的一个用户界面中显示。下面是代码

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setIgnoringComments(true);
inputStream = new FileInputStream(new File(filename));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
Element rootNode = doc.getDocumentElement();
if(filename.endsWith("items.xml"))//load the enabled items
{
    NodeList nList = doc.getElementsByTagName("item");
    for(int i = 0; i < nList.getLength(); i++)
    {
        try
        {
            Node node = nList.item(i);
            if((node.getNodeType() == Node.ELEMENT_NODE))
            {
                Element ele = (Element)node;
                String access = (String)ele.getAttribute("access");
                String level = access.substring(0,access.indexOf("."));

                if(!LevelManager.isLevelEnabled(level))
                {
                    rootNode.removeChild(node);
                }
            }
            else
            {
                System.out.println("NO ELEMENT NODE");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
doc.normalize();
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
serializer.transform(new DOMSource(doc), new StreamResult(stw));
discfeatures = stw.toString();
return discfeatures;
}
catch(Exception w)
{
}

Now, the issue is ---> sometimes nodes are not removing.Say for example if I remove server1 attribute node -- its removed. 现在,问题是--->有时节点没有删除。例如,如果我删除server1属性节点 - 它被删除。 and then I again try to remove server2 attribute node.it shows server1 node which should'nt.Please let me know if I am using the proper way of removing the node. 然后我再次尝试删除server2属性node.it显示server1节点,不应该。如果我使用正确的方法删除节点,请告诉我。

Thanks 谢谢

I just realized that in the for loop, once I remove the node the total size of the xml node decrease by 1 and xml structure re-arrange's..so it will advance 1 node futher. 我刚刚意识到在for循环中,一旦我删除了节点,xml节点的总大小减少1并且xml结构重新排列。所以它将进一步前进1个节点。 I changed my code as 我改变了我的代码

for(int i =0 ; i < nList.getLength();)
{
   //operation/

  //remove case match
   {
     //remove
     i=0;
     contiune;
   }
  i++
}

This worked for me!!! 这对我有用!!!

When you remove a node in node list, the DOM rearrange it and your index will be wrong. 当您删除节点列表中的节点时,DOM会重新排列它并且您的索引将是错误的。

NodeList and NamedNodeMap objects in the DOM are live; DOM中的NodeList和NamedNodeMap对象是实时的; that is, changes to the underlying document structure are reflected in all relevant NodeList and NamedNodeMap objects. 也就是说,对底层文档结构的更改将反映在所有相关的NodeList和NamedNodeMap对象中。

The kiddo's solution worked but it may be ineffective. kiddo的解决方案有效,但可能无效。 So I just edit it a little bit. 所以我只是编辑一下。

int j = 0;
for(int i =0 ; i < nList.getLength();)
{
   //operation/

  //remove case match
   {
     //remove
     i=j;
     continue;
   } else {
     j++;
   }
  i++
}

I did try it and it worked for me. 我确实尝试过,它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM