QDomDocument is just confusing me!
-
I am pulling my hair out, I just cant seem to wrap my head around this QDomDocument. The Qt Example is fine for reading an xml file and displaying its first children, but the explanation is so limited for me, I cant see how to expand it to what I need.
can someone give me a clear cut way to read an XML file into a QDomDocument, modify an item within this QDomDocument, and write the changed XML file back to disk?
For instance, if I had a XML file:
@
<Family>
<Mike>
<Age>20</Age>
<Mikes_Kid>
<Age>5</Age>
</Mikes_Kid>
</Mike>
<Jenny>
<Age>30</Age>
<Jennys_Kid>
<Age>20</Age>
<Jennys_Kids_Kid>
<Age>5</Age>
</Jennys_Kids_Kid>
</Jennys_Kid>
</Jenny>
</Family>
@Suppose I had a tree like this...how is is possible to load an unknown number of children and siblings into a QdomDocument, then modify one of them not knowing where they are located or named, and write it back to disk?
Its messing with my mind.
-
Hi there,
The simple answer to your question is the following example where Jenny's Kid's Age is changed from 20 to 21:
@
#include <QtCore/QCoreApplication>
#include <QtXml>
#include <QDebug>int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);QDomDocument doc; QFile xmlFile("/Users/rob/Documents/PyQt/family.xml"); QByteArray xml; if(xmlFile.open(QFile::ReadOnly)){ xml=xmlFile.readAll(); xmlFile.close(); else return 1; doc.setContent(xml); QDomNode family=doc.firstChild(); QDomElement jenny=family.firstChildElement("Jenny"); QDomElement jennysKid=jenny.firstChildElement("Jennys_Kid"); QDomElement jennysKidAge=jennysKid.firstChildElement("Age"); QDomText jennysKidAgeText=jennysKidAge.firstChild().toText(); jennysKidAgeText.setData("21"); qDebug() << doc.toString();
}
@The complex answer is that usually you would use QtXml to iteratively parse the document into a C++ nested data structure (QTreeWidget or a model), which allows for easier handling and faster searching and modification and then use QtXml to write the modified structure back to the file after modification.
Hope this helps ;o)
-
Thank you for this example, its helps some, but I see as I dig into this, there is a lot for me to learn. I will look into the QTreeWidget also. Maybe that is what I am looking for.
-
I just had a thought, and probably a really bad one, but I have to ask. Is it possible to have a class, for example with this example of the family and age.
If I had a class with the name and age as variables. if I dig my way through the QDom Tree and find the name and age of a person. Is is possible to store this class in something like a QVector<class> and use a signal mapper to link a signal in the class to another function that will update the QDom tree?
I am trying to learn about these things and I know I am very lacking in it. So my idea might not be possible or maybe not the best way. I am trying to achieve some sort of data binding so I dont really have to know a specific "name" in the xml file in order to make a change.