tags:

views:

97

answers:

2

Hi I am working on an application which reads XML file. Here I am trying to read "name" node under the "a"node not under the node "b". When I tried to read the root "name" node I get both nodes. Please help me to solve the problem. Bellow is the sample.

 <a>    
      <x>rrr</X>
      <b>
        <name> 123 </name>
      </b>
      <name> main </name>
      <c>yyyy</c>
    </a>





    QDomDocument mDocument;
     QDomElement  mDocumentElement;
     if (!mDocument.setContent(file.readAll())) 
     {          
         return ;      
     }      

     mDocumentElement = mDocument.documentElement();
     QDomNodeList list  = mDocumentElement.elementsByTagName("a").at(0).toElement().elementsByTagName("name");

     int count = list.count();
     for (int i = 0; i < count; i++)
     {
      QString str = list.at(i).nodeValue();
      QMessageBox::information(this, "text", str, QMessageBox::Yes, 0);
     }
A: 

If your XML traversal is based on the structure and not based on the content type, you can follow this..

QDomDocument mDocument;
QDomElement  mDocumentElement;
if (!mDocument.setContent(file.readAll())) 
{          
    return ;      
}      

mDocumentElement = mDocument.documentElement();
QDomNodeList list = mDocumentElement.childNodes();
QDomElement firstChild = list.at(0).toElement(); // will return the first child
QDomElement secondChild = list.at(1).toElement(); // second child
   ......

To obtain the data present in between the tags,

QString childData = firstChild.text();

can be used. Similarly, You can traverse till your desired <name> and its value can be used. Remember childNodes() will return only the list of direct childs. Hope am clear. It isn't tested but should work.

liaK
A: 

You can iterate over direct children of the "a" element using QDomNode::firstChild(QString tagName) and QDomNode::nextSiblingElement(QString tagName). The code will looks like:

QDomDocument mDocument;
if (!mDocument.setContent(file.readAll())) 
{          
    return ;      
}

QDomElement  mElement = mDocument.documentElement().firstChildElement("name");
while ( !mElement.isNull() )
{
    // do all you need to do with <name> element
    mElement = mElement.nextSiblingElement("name");
}

I've tested this code on your example XML and it works if you'll fix tag mismatch on this line: <x>rrr</X>

VestniK