c++qtqtxml

Importing XML to DOM tree in Qt


I'm using Qt 4.7 on Mac OS X, and I have a QString containing a path to an XML file. I would like to import that file into a DOM tree and store the data as a member variable to a class. What is the best way to do this?

I've been looking at the QtXml documentation, but I can't find a clear way to convert from the QXml* classes to the QDom* classes.


Solution

  • I don't think you need to bother with the QXml* classes to traverse the DOM.

    The QDomDocument class has a setContent() method that can take an open QFile.

    There's a code sample in the "Details" section of the QDomDocument documentation.

    QDomDocument doc("mydocument");
    QFile file("mydocument.xml");
    if (!file.open(QIODevice::ReadOnly))
        return;
    if (!doc.setContent(&file)) {
        file.close();
        return;
    }
    file.close();
    
    // print out the element names of all elements that are direct children
    // of the outermost element.
    QDomElement docElem = doc.documentElement();
    
    QDomNode n = docElem.firstChild();
    while(!n.isNull()) {
        QDomElement e = n.toElement(); // try to convert the node to an element.
        if(!e.isNull()) {
            cout << qPrintable(e.tagName()) << endl; // the node really is an element.
        }
        n = n.nextSibling();
    }