简体   繁体   English

使用Stax API Java修改xml文件

[英]modify xml file with Stax API Java

I'm very new in XML, and I try to modify an xml file. 我是XML的新手,我尝试修改xml文件。 Let me explain what I want do. 让我解释一下我想做什么。 I have an existing file, in wich are writed few lines, but i want to keep them and add other ones. 我有一个现有文件,只写了几行,但我想保留它们并添加其他行。

My example is not working in the way I want. 我的示例无法按照我想要的方式工作。 It's delete every thing, and write a new XML. 它删除所有内容,并编写新的XML。

What I need to read to know how to do that? 我需要阅读什么才能知道该怎么做?

This is my java code: 这是我的Java代码:

public static void WriteFile(){
          try{
              XMLOutputFactory  xMLOutputFactory  = XMLOutputFactory.newFactory();
              XMLStreamWriter xMLStreamWriter = xMLOutputFactory.
                      createXMLStreamWriter(new FileOutputStream("src\\data\\orders.xml"));
              xMLStreamWriter.writeStartDocument("1.0");
              xMLStreamWriter.writeStartElement("products");
              xMLStreamWriter.writeStartElement("product");

              //set description
              xMLStreamWriter.writeStartElement("description");
              xMLStreamWriter.writeCharacters("Apple MacBook Air A 11.6 Mac OS X v10.7 Lion MacBook");
              xMLStreamWriter.writeEndElement();
               //end description

              //set price
              xMLStreamWriter.writeStartElement("price");
              xMLStreamWriter.writeAttribute("currency","USD");
              xMLStreamWriter.writeCharacters("999");
              xMLStreamWriter.writeEndElement();
              //end price

              xMLStreamWriter.writeEndElement();
              //end produtcs
              xMLStreamWriter.writeEndElement();
              //end produtc
              xMLStreamWriter.flush();
              xMLStreamWriter.close();
          }catch (Exception e){
              System.out.println(e.getMessage());
          }
      }

Your code uses XML Stream Writer to write some data in a file location. 您的代码使用XML Stream Writer在文件位置中写入一些数据。 The fact that the file exists and happens to contain XML is irrelevant as your code will simply overwrite it. 该文件存在并恰好包含XML的事实无关紧要,因为您的代码将简单地覆盖它。

What you do now is: 您现在要做的是:

  1. write the new content 写新内容

What you need is: 您需要的是:

  1. read the content of the existing file 读取现有文件的内容
  2. write the old content 写旧内容
  3. write the new content 写新内容
  4. save the file 保存文件

For steps 2, 3 and 4 you could use a new file and then overwrite the old one. 对于步骤2、3和4,您可以使用一个新文件,然后覆盖旧文件。

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

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