Java HTML/XML - 如何刪除元素和他們的孩子從Xml與Stax
我們想知道如何刪除元素和他們的孩子從Xml與Stax。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
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);
}
}
}
}