简体   繁体   English

编辑XML文件Java

[英]Editing xml file java

Quick question on stAX xml reader and writer. 关于stAX xml读取器和写入器的快速问题。

Following on from a previous question on how to Edit one part of an xml file using stAX, this is what I am doing: 接下来是关于如何使用stAX编辑xml文件的一部分的上一个问题,这就是我正在做的事情:

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. 但是,为此,我要创建一个新文件-bla2.xml。 Is this necessary? 这有必要吗?
  • Will stAX just allow me to write to the original file bla1.xml? stAX将只允许我写入原始文件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? 正确?

On this line: 在这行上:

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

Change bla2.xml to simply bla.xml. 将bla2.xml更改为bla.xml。 The new file will then overwrite the previous one. 然后,新文件将覆盖前一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM