I want to append data to an XML file using OutputStreamWriter but ending up something like below
<?xml version="1.0" encoding="utf-8"?>
<doc>
<msg>
<tag1>data1</tag1>
...
</msg>
</doc>
<?xml version="1.0" encoding="utf-8"?>
<doc>
<msg>
<tag1>data2</tag1>
...
</msg>
</doc>
How can I achieve the correct format
<?xml version="1.0" encoding="utf-8"?>
<doc>
<msg>
<tag1>data1</tag1>
...
</msg>
<msg>
<tag1>data2</tag1>
...
</msg>
</doc>
I have tried with below code
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
File file = new File(outputFile);
Writer fw = null;
XMLStreamWriter w = null;
try {
if(!file.isFile()) {
file.createNewFile();
}
fw = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
w = outputFactory.createXMLStreamWriter(fw);
w.writeStartDocument("utf-8", "1.0");
w.writeStartElement("doc");
createMessageElement(fingerPrint, w, data);//method to write data
w.writeEndElement();
w.writeEndDocument();
w.flush();
w.close();
w.close();
fw.flush();
fw.close();
Please give me suggestion. I'm new to StAX.
Your example is only appending a new xml document to the end of a file. If you want to append data to an existing xml doc you have to read the source xml, and write it to another file, inserting your new element as need.... see http://docs.oracle.com/javase/tutorial/jaxp/stax/example.html#bnbgq for an example using stax api.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With