Basic solution, not including namespacing or attributes
- Uses XMLStreamWriter to sink content from handler into one output
- Skips over root elements so we don't put them in output twice
Code
public class XmlMerger {
public static void main(String[] args) throws Exception {
FileOutputStream outputStream = new FileOutputStream("output.xml");
XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(new OutputStreamWriter(outputStream));
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
Handler handler = new Handler(out);
out.writeStartDocument();
out.writeStartElement("root");
saxParser.parse(new File("input1.xml"), handler);
saxParser.parse(new File("input2.xml"), handler);
out.writeEndElement();
out.close();
}
private static class Handler extends DefaultHandler {
private XMLStreamWriter out;
private boolean dumping;
public Handler(XMLStreamWriter out) {
this.out = out;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("root".equals(qName)) {
dumping = true;
} else {
try {
out.writeStartElement(qName);
// TODO attributes if you need them...
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("root".equals(qName)) {
dumping = false;
} else {
try {
out.writeEndElement();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (!dumping) {
return;
}
try {
out.writeCharacters(ch, start, length);
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
}