<...">

Update XML file in QT

I have an xml file

<root rootname="RName" otherstuff="temp"> <somechild childname="CName" otherstuff="temp"> </somechild> </root> 

in the above XML, how can I upgrade RName to RN and CName to CN using QT. I am using QDomDocument but cannot complete the required thing.

+4
source share
1 answer

This will help if you share information about how you use QDomDocument, and which part is exactly complex. But here is how this happens in general:

  • the file is read from the file system;

  • the file is parsed in a QDomDocument;

  • The contents of the document are changed.

  • data is 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(); 

Please note that in real applications you will want to save the data in another file, make sure that the save was successful, and then replace the original file with a copy.

+9
source

Source: https://habr.com/ru/post/1436779/


All Articles