Blubber blubber zisch - Motivation... XML in 10 points
Here is an example of an XML file used by Columbo to describe a search site on the Internet:
Now let us have a look how such a file is parsed. The easiest way is to create a QDomDocument. With its constructor QDomDocument(const QString& name), the filename with the name name will be completely parsed, and you can navigate on the file content as a tree structure. As a first step, we check if the file has the correct document type:
1 QDomDocument doc(filename); 2 if (doc.doctype().name() != "search") { 3 cout << "Not the correct document type." << endl; 4 return; 5 } 6 |
The root element (which is an instance of the class QDomElement) is available via the method QDomDocument::documentElement(). The attributes of the element can be asked for with the method QDomElement::attribute(), which returns a QString. We output the "name" and "method" attributes, which in the file in the above example are "Altavista", "get" resp.:
1 QDomElement docel = doc.documentElement(); 2 cout << "Name: " << docel.attribute("name").latin1() << endl; 3 cout << "Method: " << docel.attribute("method").latin1() << endl; 4 |
The root element has some <input> children. In order to process all of them, you can iterate over them with a code piece like the following:
1 QDomElement childel = docel.firstChild().toElement() 2 while (!childel.isNull()) { 3 if (childel.tagName() == "input") { 4 // do something with element childel 5 } 6 childel = childel.nextSibling().toElement(); 7 } 8 |
The use of the toElement() method is necessary because QDomElement::firstChild() returns an object of class QDomNode, which has to be converted to an element first.
In some cases, you do not want to iterate over the children of an element, but access a child with a certain tag name directly. Continuing with the above example, this can be achieved as follows:
1 QDomElement interpretel = docel.namedItem("interpret").toElement(); 2 if (!interpret.isNull()) { 3 // do something with interpretel 4 } 5 |