Pergunta

Quick question on stAX xml reader and writer.

Following on from a previous question on how to Edit one part of an xml file using stAX, this is what I am doing:

XMLInputFactory inFactory = XMLInputFactory.newInstance();
XMLEventReader eventReader = inFactory.createXMLEventReader(new FileInputStream("bla.xml"));
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLEventWriter writer = factory.createXMLEventWriter(new FileWriter(new file("bla2.xml));
XMLEventFactory eventFactory = XMLEventFactory.newInstance();

while (eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();
    writer.add(event);

if (condition) create and add other events } … …. This way it copies the file however makes alterations if a condition is matched.

  • However, to do this I am creating a new file - bla2.xml. Is this necessary?
  • Will stAX just allow me to write to the original file bla1.xml?
  • If not then I'm assuming I would have to create the new file, delete the old one and rename the new to the same as the previous. correct?
Foi útil?

Solução

On this line:

XMLEventWriter writer = factory.createXMLEventWriter(new FileWriter(new file("bla2.xml));

Change bla2.xml to simply bla.xml. The new file will then overwrite the previous one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top