Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用StAX将元素添加到现有XML文件中?_Java_Xml_Stax - Fatal编程技术网

Java 如何使用StAX将元素添加到现有XML文件中?

Java 如何使用StAX将元素添加到现有XML文件中?,java,xml,stax,Java,Xml,Stax,我有一个类似于下面的XML文件: <?xml version="1.0" encoding="UTF-8"?> <a> <b id="1">xxx</b> <b id="2">yyy</b> <b id="3">zzz</b> </a> 有没有办法用StAX解析器在zzz之后添加一个元素,比如ddd? 我想到的方法是将XML的第一部分写入一个新文件,如下所示 <?xml

我有一个类似于下面的XML文件:

<?xml version="1.0" encoding="UTF-8"?>  
<a>  
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
</a>  
有没有办法用StAX解析器在zzz之后添加一个元素,比如ddd? 我想到的方法是将XML的第一部分写入一个新文件,如下所示

<?xml version="1.0" encoding="UTF-8"?>  
<a>  
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>

但我无法找到一个在最后一个元素zzz之后准确写入的解决方案。是否需要再次打开新文件进行输出?是否可以使用StAX进行此操作?

一个示例,说明如何自己进行此操作:

public static void addElementToXML(String value){

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = null;
      Document doc = null;
      try {

        String filePath = "D:\\Loic_Workspace\\Test2\\res\\test.xml";
        db = dbf.newDocumentBuilder();
        doc = db.parse(new File(filePath));
        NodeList ndListe = doc.getElementsByTagName("b");

        Integer newId = Integer.parseInt(ndListe.item(ndListe.getLength()-1).getAttributes().item(0).getTextContent()) + 1;

        String newXMLLine ="<b id=\""+newId+"\">"+StringEscapeUtils.escapeXml(value)+"</b>";

        Node nodeToImport = db.parse(new InputSource(new StringReader(newXMLLine))).getElementsByTagName("b").item(0);

        ndListe.item(ndListe.getLength()-1).getParentNode().appendChild(doc.importNode(nodeToImport, true));

          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.INDENT, "yes");  

          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(new StringWriter());

         transformer.transform(source, result);


          Writer output = new BufferedWriter(new FileWriter(filePath));
          String xmlOutput = result.getWriter().toString();  
          output.write(xmlOutput);
          output.close();


      } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}
请注意,我使用了中的StringEscapeUtils方法

在以下日期之前提交文件:

在以下日期后存档:


是的,您需要一个临时文件来写入。下面是一个如何使用StAX执行此操作的示例:

Path in = Paths.get("file.xml");
Path temp = Files.createTempFile(null, null);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
try (FileWriter out = new FileWriter(temp.toFile())) {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileReader(in.toFile()));
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
    int depth = 0;
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        int eventType = event.getEventType();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (eventType == XMLStreamConstants.END_ELEMENT) {
            depth--;
            if (depth == 0) {
                List<Attribute> attrs = new ArrayList<>(1);
                attrs.add(eventFactory.createAttribute("id", "4"));
                writer.add(eventFactory.createStartElement("", null, "b", attrs.iterator(), null));
                writer.add(eventFactory.createCharacters("ddd"));
                writer.add(eventFactory.createEndElement("", null, "b"));
                writer.add(eventFactory.createSpace(System.getProperty("line.separator")));
            }
        }
        writer.add(event);
    }
    writer.flush();
    writer.close();
} catch (XMLStreamException | FactoryConfigurationError e) {
    throw new IOException(e);
}
Files.move(temp, in, StandardCopyOption.REPLACE_EXISTING);
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>  
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
</a>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<a>  
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
<b id="4">&amp; dqsd apzeze /&lt;&gt;'</b>
</a>
Path in = Paths.get("file.xml");
Path temp = Files.createTempFile(null, null);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
try (FileWriter out = new FileWriter(temp.toFile())) {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileReader(in.toFile()));
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(out);
    int depth = 0;
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        int eventType = event.getEventType();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            depth++;
        } else if (eventType == XMLStreamConstants.END_ELEMENT) {
            depth--;
            if (depth == 0) {
                List<Attribute> attrs = new ArrayList<>(1);
                attrs.add(eventFactory.createAttribute("id", "4"));
                writer.add(eventFactory.createStartElement("", null, "b", attrs.iterator(), null));
                writer.add(eventFactory.createCharacters("ddd"));
                writer.add(eventFactory.createEndElement("", null, "b"));
                writer.add(eventFactory.createSpace(System.getProperty("line.separator")));
            }
        }
        writer.add(event);
    }
    writer.flush();
    writer.close();
} catch (XMLStreamException | FactoryConfigurationError e) {
    throw new IOException(e);
}
Files.move(temp, in, StandardCopyOption.REPLACE_EXISTING);