PDA

View Full Version : QDomDocument and reading XML



prashant
12th September 2009, 15:56
Hi,

First time using QT and XML. Here is my simple XML file.


<?xml version="1.0"?>

<Node nodetype="atomic"
header="atomic.h">

<Input name="inNumber" type="color" value="0.2,0.3,0.5"/>
<Output name="outNumber" type="float" value="0.5"/>

</Node>


and here is the QT code:


QFile file("atomic.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return 0;

QDomDocument doc;
if (!doc.setContent(&file)) {
file.close();
return 0;
}
file.close();

QDomNode n = doc.firstChild();

while(!n.isNull()) {

if(n.isElement()) {

QDomElement e = n.toElement();
QString name = e.tagName();

qDebug() << name;

if(name == "Node") {

QString nodeType = e.attribute("nodetype","");
QString header = e.attribute("header","");
qDebug() << nodeType << header;

} else if(name == "Input") {

QString name1 = e.attribute("name","");
QString type1 = e.attribute("type","");
QString value1 = e.attribute("value","");

qDebug() << name1 << type1 << value1;
}
}
n = n.nextSibling();
}


Problem 1
The code is not entering in condition:

else if(name == "Input") {

Cheers

Prashant

estanisgeyer
12th September 2009, 16:14
Hi,

The tag "Input" is child the node "Node". Is its problem.

Marcelo E. Geyer

prashant
12th September 2009, 17:17
Not able to get the child nodes of "Node" this way:


for(signed i(0); i<n.childNodes().count();i++){

QDomNode childNode = n.childNodes().item(i);
QDomElement e = childNode.toElement();
QString name = e.tagName();
if(name == "Input") {

QString name1 = e.attribute("name","");
QString type1 = e.attribute("type","");
QString value1 = e.attribute("value","");

qDebug() << name1 << type1 << value1;
}


It's because:


n.hasChildNodes(); // = 0

prashant
20th September 2009, 12:42
I didn't find any solution so far. May be some one point out the solution.

Cheers

Prashant

faldzip
20th September 2009, 14:14
chage this:


QDomNode n = doc.firstChild();

to this:


QDomElement e = doc.documentElement(); // now e contains "Node" - it's a document element - means root element

and use QDomElements if you want to get only elements. You can iterate through "Node" childs like this:


QDomElement child = e.firstChildElement();
while (!child.isNull()) {
// do sth with child
// it should be "Input" in first iteration and "Output" in second one
child = child.nextSiblingElement(); // move 'child' to be the next sibling element
}