Search code examples
javaxmlxercesdomparser

Remove XML node using Java SE


How to remove XML nodes in Java SE? I am using org.apache.xerces. Thanks. The below code isn't working.

DOMParser parser = new DOMParser();
System.out.println(DIR_STRING + "/" + jmsFileNameString);
parser.parse(DIR_STRING + "/" + jmsFileNameString);
Document doc = parser.getDocument();
NodeList list = doc.getElementsByTagName("*");
for (int i = 0; i < list.getLength(); i++) {
    if (list.item(i).getNodeName().matches(HEADER_REGEXP)) {
        list.item(i).getParentNode().removeChild(list.item(i)));
    }
}

Solution

  • It does work; however, it doesn't save to the XML file. The changes are saved in the Document object.

    To save to the Document object in a file:

        OutputFormat of = new OutputFormat("XML","UTF-8",true);
        XMLSerializer serializer = new XMLSerializer();
        serializer.setOutputFormat(of);
        serializer.setOutputByteStream(new FileOutputStream(PATH));
        serializer.serialize(doc);