Reputation: 497
I am a newbie to Qt and I want to update(add new nodes and attributes) a xml file using Qt 4 and QxmlStreamwriter, but Append open mode sets the cursor in file after the enddocument line...
Is there anyway to achieve that using QXmlStreamWriter? If so, please give me an example code
Upvotes: 0
Views: 2012
Reputation: 8147
You will need to re-write the file with the extra nodes. The stream interface (QXmlStreamReader
/ QXmlStreamWriter
) is more complex to use to do this than the DOM (QDomDocument
) interface, but has the benefit of lower memory requirements.
With the DOM interface you work with an in-memory representation of the XML document. With the stream interface you may need to build and maintain your own representation.
Sample code for the stream interface:
QFile inputFile("in.xml");
if (! inputFile.open(QIODevice::ReadOnly))
// error handling
QFile outputFile("out.xml");
if (! outputFile.open(QIODevice::WriteOnly))
// error handling
QXmlStreamReader inputStream(&inputFile);
QXmlStreamWriter outputStream(&outputFile);
while (! inputStream.atEnd())
{
inputStream.readNext();
// manipulation logic goes here
outputStream.writeCurrentToken(inputStream);
}
Sample code for the DOM interface:
QFile inputFile("in.xml");
if (! inputFile.open(QIODevice::ReadOnly))
// error handling
QDomDocument doc;
if (! doc.setContent(&inputFile))
// error handling
// manipulation logic goes here
QFile outputFile("out.xml");
if (! outputFile.open(QIODevice::WriteOnly))
// error handling
outputFile.write(doc.toByteArray());
Upvotes: 1