Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Contributor
Dhanya
Posts: 21
Registered: ‎09-23-2012
My Device: BB10 Dev Alpha Device
Accepted Solution

Writing dynamically obtained data into XML ?

I need to persist app data into an xml in the below format
<root>
<employee name="abc"/>
<employee name="xyz"/>
<employee name="hij"/>
</root>

 

But when I am using the below code, I am getting the below format. It keeps on creating a new root node.
<root>
<employee name="abc"
</root>
<root>
<employee name="xyz"
</root>
<root>
<employee name="hij"
</root>

 

Below is the code I wrote using QDomDocument

const int Indent = 4;
QString x = tx->text(); // is the employee name
QString appFolder(QDir::currentPath());
QString fileName = appFolder + "/app/native/assets/data.xml";
QFile file(fileName);
file.open(QIODevice::ReadWrite);
QByteArray xmlData(file.readAll());
QDomDocument doc;
doc.setContent(xmlData);
QDomElement root = doc.documentElement();
if (root.isNull()) {
root = doc.createElement(QString("root"));
}
QDomElement tag = doc.createElement(QString("employee"));
tag.setAttribute("name", x);
root.appendChild(tag);

QTextStream stream;
stream.setDevice(&file);
doc.save(stream, Indent);
file.close();
}

 

Please help me out in solving this issue.
Before starting with QDomElement, II have also worked on QXmlStreamWriter but failed to get the required format.

Contributor
Dhanya
Posts: 21
Registered: ‎09-23-2012
My Device: BB10 Dev Alpha Device

Solved the issue  :smileyhappy:   const int Indent = 4; Q...

Solved the issue  :smileyhappy:

 

const int Indent = 4;
QString x = tx->text();
QString appFolder(QDir::currentPath());
QString fileName = appFolder + "/app/native/assets/data.xml";


QFile file(fileName);
file.open(QIODevice::ReadWrite);

QByteArray xmlData(file.readAll());
QDomDocument doc;
doc.setContent(xmlData);

QDomElement root = doc.documentElement();

if (root.nodeName().isEmpty()) {
root = doc.createElement(QString("root"));
doc.appendChild(root);
}

 

QDomElement tag = doc.createElement(QString("employee"));
tag.setAttribute("name",x);
root.appendChild(tag);

 

file.resize(0);
QTextStream stream;
stream.setDevice(&file);
doc.save(stream, Indent);

file.close();

 

Regards,

Dhanya

 

Contributor
Thunderbuck
Posts: 20
Registered: ‎04-25-2011
My Device: PlayBook - 64GB, Bold 9900, Dev Alpha

Re: Solved the issue :smileyhappy: const int Indent = 4; Q...

That's kinda awesome!

 

Thanks for posting that; I'm working on a project where I'll have to persist XML data.  This code is great to have.