Remove a child of root of XML using java

2020-05-08 05:51发布

This is my xml file.

- <deviceparameters>
       - <parameter componenttype="TextBox">
         <name>Operating Type</name> 
         <oid>1.3.6.1.4.1.31163.5.1.1</oid>  
         <writable>true</writable> 
         <description>The operating type defines which waveform type is used. This configuration takes several seconds to execute</description> 
       - <paramvalues type="Integer">
            <value default="No">123</value> 
         </paramvalues>
         </parameter>

       - <parameter componenttype="TextBox">
         <name>Active Waveform Status</name> 
         <oid>1.3.6.1.4.1.31163.5.1.2</oid> 
         <writable>false</writable> 
         <description>Show the status of the waveform configured by operatingType</description> 
       - <paramvalues type="String">
            <value default="yes">Active</value> 
      </paramvalues>
      </parameter>
    </deviceparameters>

I want to remove node with name 'Active wavwform Status'. How can I reomve that particular node from xml.

The code I have written is below.

rootElement = doc.getDocumentElement();
NodeList nList = doc.getElementsByTagName("parameter");
String nodeName = TF_name.getText();


System.out.println(""+nList.getLength());

for (int temp = 0; temp < nList.getLength();temp++)                
{
    Node nNode =  nList.item(temp);    
    Element eElement = (Element) nNode;
    String upname1 = getTagValue("name", eElement);

    if(upname1.equals(nodeName))
    {
        System.out.println("Parent:   "+nNode.getParentNode().getNodeName());
        System.out.println("nodename: "+nNode.getNodeName());
        System.out.println("rmoving ....");

        rootElement.removeChild(nNode);

        System.out.println("removed..."); 
    }                   
}                   

3条回答
▲ chillily
2楼-- · 2020-05-08 06:35

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);
查看更多
放荡不羁爱自由
3楼-- · 2020-05-08 06:40

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.

查看更多
Melony?
4楼-- · 2020-05-08 06:56

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");
    }
}
查看更多
登录 后发表回答