这是我试图合并合并多个 XML 文件的代码。
public static void mergeXml(String directory) throws Exception {
File dir = new File(directory);
File[] rootFiles = dir.listFiles();
XMLEventWriter eventWriter;
XMLEventFactory eventFactory;
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("temp/testMerge1.xml"));
eventFactory = XMLEventFactory.newInstance();
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument("ISO-8859-1");
eventWriter.add(startDocument);
for(File rootFile : rootFiles){
XMLEventReader test = inputFactory.createXMLEventReader(new StreamSource(rootFile));
while(test.hasNext()){
XMLEvent event= test.nextEvent();
//avoiding start(<?xml version="1.0"?>) and end of the documents;
if (event.getEventType()!= XMLEvent.START_DOCUMENT && event.getEventType() != XMLEvent.END_DOCUMENT)
eventWriter.add(event);
test.close();
}
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
}
}
我遇到了两个问题
- 输出文件没有任何编码
- 当我试图解析此代码创建的文件时,出现以下异常
[Fatal Error] :1:2493: The markup in the document following the root element must be well-formed.
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at SplitMain.validateInputFile(SplitMain.java:139)
at SplitMain.main(SplitMain.java:76)