RandomDisplayName
RandomDisplayName

Reputation: 281

Browse through XML tags using QDomElement

I have to parse xml file's with the following format:

<FirstTag>
    <SecondTag>
        <Attribute value="hello"/> 
    </SecondTag>
</FirstTag>

Now this is what I have:

QDomNode n = domElem.firstChild();
while(!n.isNull()){
  QDomElement e = n.toElement();
  if(!e.isNull()){
    if(e.tagName() == "FirstTag"){
      //secondtag???
    }
  }
n = n.nextSibling();
}

Now to my actual question: I want to access an attribute from SecondTag, how can I access that, because its a sub tag from FirstTag I cant access it in my current loop.

Upvotes: 1

Views: 1519

Answers (3)

Jablonski
Jablonski

Reputation: 18504

It is very simple XML doc, so try this. This code works as you want

QDomDocument doc("mydocument");
QFile f("G:/x.txt");
if (!f.open(QIODevice::ReadOnly))
    qDebug()  <<"fail";
if (!doc.setContent(&f)) {
    f.close();
    qDebug() <<"fail";
}
f.close();

QDomElement domElem = doc.documentElement();//FistTag here
QDomNode n = domElem.firstChild();//seconTag here
  QDomElement e = n.toElement();
  if(!e.isNull()){
      n = n.firstChild();//now it is attribute tag

      e = n.toElement();
        qDebug() << e.attribute("value") <<"inside" << e.tagName();
  }

Output: "hello" inside "Attribute"

Upvotes: 1

TheDarkKnight
TheDarkKnight

Reputation: 27611

It looks like you've missed that QDomNode has child nodes and a function childNodes() to get the children of a node.

So, if QDomNode n is pointing to the first element, rather than looking for just the first Child, get the child nodes of each element, checking for the right node name and then the child nodes of each child. To get the attribute, you'd do something like this:-

QString attribValue;
QDomNodeList children = n.childNodes();

QDomNode childNode = children.firstChild();
while(!childNode.isNull())
{
    if(childNode.nodeName() == "Attribute")
    {    // there may be multiple attributes
         QDomNamedNodeMap attributeMap = node.attributes();

         // Let's assume there is only one attribute this time
         QDomAttr item = attributeMap.item(0).toAttr();
         if(item.name() == "value")
         {
            attribValue = item.value(); // which is the string "hello"
         } 
    }       
}

This could be done with a recursive function, for each node and its children.

Upvotes: 1

Silicomancer
Silicomancer

Reputation: 9156

Don't do it that way. First use documentElement() then (on the returned object) search for the nested elements using elementsByTagName().

Upvotes: 0

Related Questions