Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending data to an XML file using OutputStreamWriter (StAX parser)

Tags:

java

xml

stax

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.

like image 883
user3136136 Avatar asked Mar 14 '26 07:03

user3136136


1 Answers

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.

like image 109
P.A. Cros Avatar answered Mar 15 '26 19:03

P.A. Cros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!