Java HTML / XML How to - Remove elements and their children from Xml with Stax








Question

We would like to know how to remove elements and their children from Xml with Stax.

Answer

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/*from   w w  w. j  a  v  a 2s. c o m*/
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.events.XMLEvent;

public class Main {
  public static void main(String[] args) throws Exception {
    File source = new File(args[0]);
    File target = new File(source + ".new");

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    InputStream in = new FileInputStream(source);
    XMLEventReader reader = inputFactory.createXMLEventReader(in);

    OutputStream out = new FileOutputStream(target);
    XMLEventWriter writer = outputFactory.createXMLEventWriter(out);
    XMLEvent event;

    boolean deleteSection = false;
    while (reader.hasNext()) {
      event = reader.nextEvent();
      if (event.getEventType() == XMLStreamConstants.START_ELEMENT
          && event.asStartElement().getName().toString()
              .equalsIgnoreCase("companies")) {
        deleteSection = true;
        continue;
      } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
          && (event.asEndElement().getName().toString()
              .equalsIgnoreCase("companies"))) {
        deleteSection = false;
        continue;
      } else if (deleteSection) {
        continue;
      } else {
        writer.add(event);
      }
    }
  }
}