我有一个巨大的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区分大小写