如何通过StAX修改巨大的XML文件?

前端之家收集整理的这篇文章主要介绍了如何通过StAX修改巨大的XML文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个巨大的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>

有任何想法吗?

尝试这个
XMLInputFactory inFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inFactory.createXMLEventReader(new FileInputStream("1.xml"));
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLEventWriter writer = factory.createXMLEventWriter(new FileWriter(file));
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        writer.add(event);
        if (event.getEventType() == XMLEvent.START_ELEMENT) {
            if (event.asStartElement().getName().toString().equalsIgnoreCase("book")) {
                writer.add(eventFactory.createStartElement("",null,"index"));
                writer.add(eventFactory.createEndElement("","index"));
            }
        }
    }
    writer.close();

笔记

新的FileWriter(file,true)附加到文件的末尾,你几乎不需要它

equalsIgnoreCase(“book”)是个坏主意,因为XML区分大小写

猜你在找的XML相关文章