简体   繁体   English

如何在Java中使用StAX修改XML元素

[英]How do I modify an XML element using StAX in Java

I want to modify my name in xml cv file, but when I use this statement: 我想在xml cv文件中修改我的名字,但是当我使用此语句时:

XMLOutputFactory xof = XMLOutputFactory.newInstance();
XMLStreamWriter xtw = null;
xtw = xof.createXMLStreamWriter(new FileWriter("eman.xml"));

all the content of the file are removed and it becomes empty. 该文件的所有内容都将被删除,并且变为空。 Basically, I want to open (eman.xml) for modification without removing its content. 基本上,我想打开(eman.xml)进行修改而不删除其内容。

关于使用stax同时读取和写入的问题,还可以在这里回答: 如何通过StAX修改巨大的XML文件?

If u want to use STAX in processing your xml file , u should know that u can only read/write from/ to xml file , but if u want to modify ur xml when exact event happen in STAX u could make processing for ur xml using DOM . 如果您想使用STAX处理您的xml文件,您应该知道您只能从xml文件读/写,但是如果您想在STAX中发生确切事件时修改ur xml,则可以使用以下命令处理ur xml DOM。 here is some example: 这是一些例子:


   XMLInputFactory factory = XMLInputFactory.newInstance();
      XMLStreamReader xmlReader= factory.createXMLStreamReader(new FileReader(fileName));
        int eventType;
       while(xmlReader.hasNext()){
              eventType=  xmlReader.next();
              if(eventType==XMLEvent.START_ELEMENT)
              {
                  QName qNqme = xmlReader.getName();
               if("YURTAG".equals(qNqme.toString()))
                {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                File file = new File("YOURXML.xml");
                Document doc = builder.parse(file);
                //make the required processing for your file.

} }

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

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