我有一个巨大的 XML (~2GB),我需要添加新元素并修改旧元素。例如,我有:
<books>
<book>....</book>
...
<book>....</book>
</books>
并想得到:
<books>
<book>
<index></index>
....
</book>
...
<book>
<index></index>
....
</book>
</books>
我使用了以下代码:
XMLInputFactory inFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inFactory.createXMLEventReader(new FileInputStream(file));
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file, true));
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.getEventType() == XMLEvent.START_ELEMENT) {
if (event.asStartElement().getName().toString().equalsIgnoreCase("book")) {
writer.writeStartElement("index");
writer.writeEndElement();
}
}
}
writer.close();
但结果如下:
<books>
<book>....</book>
....
<book>....</book>
</books><index></index>
有任何想法吗?