Remove a child of root of XML using java

情到浓时终转凉″ 提交于 2019-12-02 11:51:26

you can remove node using DocumentTraversal,NodeIterator.

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/file.xml");           
DocumentTraversal traversal = (DocumentTraversal) doc;
Node a = doc.getDocumentElement();
System.out.println("Current File Content");
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;                
    if ("parameter".equals(e.getTagName())) {
        System.out.println(""+e.getTagName() +" "+ e.getTextContent());
        b = e;
    } else if ("name".equals(e.getTagName()) && "Active Waveform Status".equals(e.getTextContent()) && b != null) {
        b.removeChild(e);
    }
}

To write new content into file

TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/file.xml"));
            iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
            b = null;
            doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("deviceparameters");
            doc.appendChild(rootElement);
            for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
                Element e = (Element) n;                 

                rootElement.appendChild(doc.importNode(n, true));

            }
            transformer.transform(source, result);

This is my suggestion on how to remove a node, including printing. You must be in the correct context, if the node to be removed isn't attached to the root you cannot remove it, as you are trying. Find the node, get its parent and remove it from the parent. The removeNode method is the important part:

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RemoveNodestuff
{
    Document doc;

    public RemoveNodestuff(String filename) throws ParserConfigurationException, SAXException,
            IOException
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new File(filename));
        print(doc.getDocumentElement());
    }

    public void removeNode(String tagName, String value)
    {
        NodeList nl = doc.getElementsByTagName(tagName);
        if (nl != null)
        {
            for (int i = 0; i < nl.getLength(); i++)
            {
                Element item = (Element) nl.item(i);
                if (item.getTextContent().equals(value))
                {
                    item.getParentNode().removeChild(item);
                }
            }
        }
        print(doc.getDocumentElement());
    }

    private void print(Node n)
    {
        NodeList nl = n.getChildNodes();
        if (nl != null)
        {
            for (int i = 0; i < nl.getLength(); i++)
            {
                Node item = nl.item(i);
                if (item.getNodeType() == Node.ELEMENT_NODE)
                {
                    System.out.println(item.getNodeName() + "  " + item.getFirstChild().getNodeValue());
                    if (item.hasChildNodes())
                    {
                        print(item);
                    }
                }
            }
        }

    }

    public static void main(String[] args) throws ParserConfigurationException, SAXException,
            IOException
    {
        RemoveNodestuff removeNodestuff = new RemoveNodestuff(
                args[0]);
        removeNodestuff.removeNode("name", "Active Waveform Status");
    }
}

I got the answer.
Actually I was deleting the node from my xml file, but I was not writing it to my xml file.
I was missing following part

TransformerFactory transformerFactory = TransformerFactory.newInstance();  
Transformer transformer = transformerFactory.newTransformer();   
DOMSource source = new DOMSource(doc);   
StreamResult result = new StreamResult(selectedFile); 
transformer.transform(source, result); 

After long time study of code I found this silly mistake, so I corrected it.
Anyways thanks for your reply.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!