0

How do we delete node and data in below xml

<test>
<abc value=10>data1</abc>
<bbc value=200>data2</bbc>
<abc value=20>
<test2>subdata1</test2></abc>
</test>

I would like to write a method which takes a parameter

deleteNode("abc")

which should be deleting all the abc nodes from the xml

desired output

<test>
<bbc value=200>data2</bbc>
</test>

Here is the updated code which i am trying

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(new File("C:\\others\\example2.xml"));
        DocumentTraversal traversal = (DocumentTraversal) doc;
        Node a = doc.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;
            if ("abc".equals(e.getTagName())) {
                a.removeChild(e);
            }
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(doc), new StreamResult(System.out));

the error which i facing

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
    at org.apache.xerces.dom.ParentNode.internalRemoveChild(Unknown Source)
    at org.apache.xerces.dom.ParentNode.removeChild(Unknown Source)
    at com.axa.qe.rtf.stepdefinition.ApiStepImplementation.I_save_try(ApiStepImplementation.java:457)
testerBDD
  • 255
  • 3
  • 18
  • Have you researched questions such as [Remove XML Node using java parser](https://stackoverflow.com/questions/3717215/remove-xml-node-using-java-parser), or [Java remove child from XML file](https://stackoverflow.com/questions/22644208/java-remove-child-from-xml-file), or [Delete a node and its elements from an XML file in java](https://stackoverflow.com/questions/33759441/delete-a-node-and-its-elements-from-an-xml-file-in-java)? Do any of those (or similar questions) help? – andrewJames Jun 06 '21 at 16:22
  • Yes, I did try all of the code and facing issue implementing them – testerBDD Jun 06 '21 at 16:32
  • Can you show us a [mre], and describe where you are getting stuck, including the text of any errors you see? That may make it easier to help you. – andrewJames Jun 06 '21 at 16:35
  • updated question with the sample code – testerBDD Jun 06 '21 at 16:45
  • What problem are you facing? What errors do you receive? – andrewJames Jun 06 '21 at 16:47
  • add to the question – testerBDD Jun 06 '21 at 16:49
  • Bear in mind that your XML sample is invalid. You need to place attribute values in quotes - so, for example, instead of this ``, you have to use this: ``. When I fix your XML and use your code, I get the following output, with no errors: `data2`. I cannot create the specific error you mention in the question. – andrewJames Jun 06 '21 at 17:09
  • You may also want to look at using XPath as shown [here](https://stackoverflow.com/a/33548746/12567365) - note how you need to iterate the nodes in reverse. – andrewJames Jun 06 '21 at 17:21

1 Answers1

0

I would suggest to use XSLT with a parameter for the task.

if the parameter has any default value in the XSLT, it will be ignored, and the one sent by Java will take precedence.

Input XML

<?xml version="1.0"?>
<test>
    <abc value="10">data1</abc>
    <bbc value="200">data2</bbc>
    <abc value="20">
        <test2>subdata1</test2>
    </abc>
</test>

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:param name="elementToRemove" select="'abc'"/>

    <xsl:template match="@*|node()">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>

    <xsl:template match="*[local-name()=$elementToRemove]"/>
</xsl:stylesheet>

Output XML

<test>
  <bbc value="200">data2</bbc>
</test>

Java

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;

public class Process {
    public static void main(String[] args) {
        String XSLTFILE = "e:/Temp/Process.xslt";
        String INFILE = "e:/Temp/Input.xml";
        String OUTFILE = "e:/Temp/Output.xml";

        try {
            StreamSource input = new StreamSource(new File(INFILE));
            StreamSource xslt = new StreamSource(new File(XSLTFILE));
            StreamResult output = new StreamResult(new File(OUTFILE));

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(xslt);
            // XSLT parameter
            transformer.setParameter("elementToRemove", "abc");
            transformer.transform(input, output);
        } catch (TransformerConfigurationException tce) {
            tce.printStackTrace();
        } catch (TransformerException te) {
            te.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Yitzhak Khabinsky
  • 18,471
  • 2
  • 15
  • 21