使用QDomDocument读取xml文件只需获取第一行

时间:2012-11-13 13:01:14

标签: c++ xml qt

我使用QXmlStreamWriter生成一个xml文件。该文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<pedestrianinfo>
    <pedestrian uuid="2112e2ed-fc9b-41e8-bbcb-b44ad78bde11">
        <module>11.1208</module>
        <direction>4</direction>
        <row>5</row>
        <column>71</column>
    </pedestrian>
    <pedestrian uuid="1aabb9c1-4aa7-4f47-9542-36d2dfaa26e4">
        <module>1.48032</module>
        <direction>4</direction>
        <row>67</row>
        <column>31</column>
    </pedestrian>

...

</pedestrianinfo>

然后我尝试通过QDomDocument阅读内容。我的代码如下所示:

xmlReader *xp = new xmlReader(QString("D:\\0T.xml"));
    if(xp->openFile()) {
        if(xp->isGetRootIndex()) {
            xp->parseRootIndexElement();
        }
        else
            cout<<"Unable to get root index."<<endl;
    }

这是isGetRootIndex():

bool xmlReader::isGetRootIndex()
{
    doc.setContent(&file,false);
    root = doc.documentElement();
    if(root.tagName() == getRootIndex()) //rootIndex=="pedestrianinfo"
        return true;
    return false;
}

这是parseRootIndexElement():

void xmlReader::parseRootIndexElement()
{
    QDomNode child = root.firstChild();
    while(!child.isNull()) {
        if(child.toElement().tagName() == getTagNameP())  //"childTagName=="pedestrian"
            parseEntryElement(child.toElement());
        qDebug()<<"module="<<module<<" direction="<<direction<<" row="<<row<<" column="<<column;
        child = child.nextSibling();
    }
}

parseEntryElement(const QDomElement&amp; element)是一个函数,用于获取每个标记中的信息并将其保存到变量(如模块)中。 但是,每次运行我的代码时,只有xml文件的第一个子节点可能是qDebug * ed *。似乎在执行child.nextSibling()之后,child变为null。为什么它没有得到下一个行人信息?

1 个答案:

答案 0 :(得分:0)

根据我在文档中看到的内容,对我来说是正确的。也许parseEntryElement意外地推进了迭代器?