Search code examples
javaxmlremovechild

Remove a child of root of XML using java


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..."); 
    }                   
}                   

Solution

  • 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.