Found at: http://publish.ez.no/article/articleprint/28/ |
Parsing XML with QT's DOM classes |
The Document Object Model (DOM) by the World Wide Web Consortium specifies a simple way of interacting with various document formats, including XML. Trolltech's Qt implements some very handy DOM classes. In this tutorial I'll demonstrate the basic principles of DOM, and give some pointers on how to use the Qt DOM classes.
<xml>
<smith>
<john/>
<susan/>
</smith>
<throckmorton>
<baldrick/>
<evangeline/>
<waldemar/>
</throckmorton>
</xml> |
|
| A simple DOM tree |
#include <qdom.h> QDomDocument doc( "myDocument" ); doc.setContent( &myFile ); // myFile is a QFile QDomElement docElement = doc.documentElement(); // docElement now refers to the node "xml" QDomNode node; node = docElement.firstChild(); // node now refers to the node "smith" node = node.firstChild(); // node now refers to the node "john" node = node.parentNode(); // node now refers to "smith" again node = node.nextSibling(); // node now refers to "throckmorton" node = node.firstChild().nextSibling(); // node now refers to "evangeline" |
<xml>
<throckmorton>
<!-- text describing Mr. Throckmorton -->
Throckmorton is a really nice guy.
</throckmorton>
</xml> |
<img src="images/img42.png" border="0" width="30" height="75" /> |
#include <qdom.h> #include <qstring.h> // Node is a QDomNode which refers to the node we are looking at QString NodeName = Node.nodeName(); QString NodeValue = Node.nodeValue(); // this gives you the value of the attribute named "src" QString srcValue = Node.attributes().nameItem( "src" ).nodeValue() // this gives you the value of the second attribute, since numbers start with 0 QString srcValue = Node.attributes().item( 1 ).nodeValue() |
#include <qdom.h>
#include <qtextstream.h>
// File is a pointer to a valid QFile object,
// Doc is a pointer to the QDomDocument
if ( File->open( IO_WriteOnly ) )
{
QTextStream stream( File );
stream << Doc->toString();
File->close();
}
|