Editing XML
-
Hi,
I have a XML like this:
@
<rootTag>
<device desc="customDevice1" type="1" id="21"/>
<device desc="customDevice2" type="2" id="22"/>
<device desc="customDevice3" type="3" id="23"/>
<function id="1">Some content function1</function>
<function id="2">Some content function2</function>
<function id="3">Some content function3</function>
</rootTag>
@I would like to modify the existing values of "function id" or any attributes of device. After modifying I need to save the same file.
Please suggest any ideas.
Thanks,
Haney. -
[quote author="Andre" date="1342523969"]
- DOM-based: [[doc:QXmlDomDocument]] and friends
[/quote]
haney, please have a look at "this example of DOM-based parsing XML":http://www.developer.nokia.com/Community/Wiki/Using_QDomDocument_to_parse_XML using "QDomDocument":http://qt-project.org/doc/qt-4.8/qdomdocument.html.
- DOM-based: [[doc:QXmlDomDocument]] and friends
-
Thanks for your replies.
I am able to use DOM based parsing XML and successfully reading the values. I want help in writing/editing in the same xml.
Eg: I just want to edit/ rewrite function id =1 CONTENT.
I want to add new device say <device desc="customDevice4" type="4" id="24"/>
DOM based parsing is really nice for reading. Please suggest me how to rewrite/modify values.
Code for Reading:
@
int main(int argc, char *argv[])
{
QApplication app(argc, argv);QFile xmlFile(":/sample.xml"); xmlFile.open(QIODevice::ReadOnly); QDomDocument doc; doc.setContent(xmlFile.readAll()); QDomElement root = doc.documentElement(); QDomElement nodeTag = root.firstChildElement("device"); while(!nodeTag.isNull()) { qDebug()<<"attributes of device"<<nodeTag.attribute("desc")<<"type" <<nodeTag.attribute("type") <<"id"<<nodeTag.attribute("id"); nodeTag = nodeTag.nextSiblingElement("device"); }
QDomNodeList nodeList = root.elementsByTagName("function");
for(int i =0;i<nodeList.count();i++)
{
QDomElement el = nodeList.at(i).toElement();qDebug()<<nodeList.at(i).toElement().text(); // prints content qDebug()<<el.attribute("id"); // prints id value
}
xmlFile.close(); return app.exec();
}
@Now that reading is fine.. I need to replace old content with new content. Also I need to modify desc of device, type, id values.
Appreciate your help in this regard.
Thanks,
Haney. -
@
el.setAttribute("id", 500);
nodeList.at(i).toElement().setNodeValue("new content");
@I just tried these two lines of code in after line num 26 in above post. I made xmlFile.open(QIODevice::WriteOnly);
but I did not see any new content in my xml file. Do I need to save it in a different way. Please share any working example of editing xml.
Thanks for the favour.
Thanks,
Haney.