user2342506
user2342506

Reputation: 1

delete nodes from XML java

I have a huge XML file and I want to delete all elements except two in java. Example :

<?xml version="1.0" encoding="windows-1252"?>
    <root>
      <c1></c1>
      <c1></c1>
      <c2></c2>
      <c3></c3>
      <c1></c1>
      .
      .
      .
      <cn></cn>
    </root>
</xml>

out put should be :

<?xml version="1.0" encoding="windows-1252"?>
    <root>
      <c1></c1>
      <c1></c1>
      <c2></c2>
      <c1></c1>
    </root>

Any help is much appreciated thnx.

Upvotes: 0

Views: 588

Answers (1)

Alpesh Gediya
Alpesh Gediya

Reputation: 3794

NodeList childeren = rootNode.getChildNodes();

remove relevant child nodes by iterating and removing desired node

  rootNode.removeChild(child)

And write back your changes to the file.

// write back to xml file

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

Upvotes: 1

Related Questions