gpt4 book ai didi

java - 合并 XML 文件时出错

转载 作者:行者123 更新时间:2023-12-01 15:01:27 27 4
gpt4 key购买 nike

这是我尝试合并多个 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();
}

}

我遇到两个问题

  1. 输出文件没有任何编码
  2. 当我尝试解析此代码创建的文件时,出现以下异常

[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)

最佳答案

// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument("ISO-8859-1");
eventWriter.add(startDocument);

这不会为输出 XML 文档创建根元素,它只是写入 <?xml声明。之后StartDocument您还需要添加合适的 StartElement :

StartElement startRootElt = eventFactory.createStartElement("", "http://example.com", "root");
eventWriter.add(startRootElt);

下一个问题是您要关闭 eventWriter在 for 循环内:

    eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
}

您需要将其移至 for 之外循环,并结束我们上面开始的根元素

}
eventWriter.add(eventFactory.createEndElement("", "http://example.com", "root"));
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();

此外,如果您的任何 XML 文件具有 <!DOCTYPE你可能会遇到问题。您可能可以像当前忽略开始和结束文档事件一样忽略 DTD 事件,但这是否有效取决于该 DTD 中声明的内容。您必须尝试一下才能看到。

关于java - 合并 XML 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13583962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com