[英]How to add an element to an existing XML files with StAX?
I have an XML file similar to the one below: 我有一个类似于以下文件的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>
Is there a way to add an element (eg. <b id="4">ddd</b>
) after <b id="3">zzz</b>
with StAX parser? 是否可以使用StAX解析器在
<b id="3">zzz</b>
之后添加元素(例如<b id="4">ddd</b>
)? The approach I have thought of is to write the first part of the XML into a new file as below. 我想到的方法是将XML的第一部分写入新文件,如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<a>
<b id="1">xxx</b>
<b id="2">yyy</b>
<b id="3">zzz</b>
But I cannot figure out a solution to write exactly after the last element ( <b id="3">zzz</b>
). 但是我想不出一个解决方案,可以在最后一个元素(
<b id="3">zzz</b>
)之后精确地写。 Do I need to open a new file for output again? 我是否需要打开一个新文件以再次输出? Is it possible to do it using StAX?
可以使用StAX做到吗?
An example of how you can do that on your own : 一个如何自己完成此操作的示例:
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();
}
}
Notice, that I've used StringEscapeUtils method from Commons Lang . 注意,我已经使用了Commons Lang的 StringEscapeUtils方法。
XMLManager.addElementToXML("& dqsd apzeze /<>'");
File before : 之前提交:
<?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>
File after : 归档后:
<?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">& dqsd apzeze /<>'</b>
</a>
Yes, you need a temp file to write to. 是的,您需要一个临时文件来写入。 Here is an example how to do this with StAX:
这是一个使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.