Update XML file in QT
qt, xml, xml-parsing
Solution
It would help if you share information how you are using QDomDocument and which part exactly is tricky. But here how it goes in general:
file is being read from a file system;
file is being parsed into QDomDocument;
content of document is being modified;
data is being saved back to the file.
In the Qt code:
// Open file
QDomDocument doc("mydocument");
QFile file("mydocument.xml");
if (!file.open(QIODevice::ReadOnly)) {
qError("Cannot open the file");
return;
}
// Parse file
if (!doc.setContent(&file)) {
qError("Cannot parse the content");
file.close();
return;
}
file.close();
// Modify content
QDomNodeList roots = elementsByTagName("root");
if (roots.size() < 1) {
qError("Cannot find root");
return;
}
QDomElement root = roots.at(0).toElement();
root.setAttribute("rootname", "RN");
// Then do the same thing for somechild
...
// Save content back to the file
if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
qError("Basically, now we lost content of a file");
return;
}
QByteArray xml = doc.toByteArray();
file.write(xml);
file.close();
Note, in real life applications you will want to save data to another file, ensure save was successful and then replace original file with a copy.
Problem
I have Xml file ``` <root rootname="RName" otherstuff="temp"> <somechild childname="CName" otherstuff="temp"> </somechild> </root> ``` in the above XML how can I update `RName` to `RN` and `CName` to `CN` using QT. I am using `QDomDocument` but not able to do required thing.