简体   繁体   中英

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:

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.

关于使用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 . 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.

} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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