• 6340阅读
  • 1回复

qt xml以elementsByTagName取Node的問題 [复制链接]

上一主题 下一主题
离线paulstrong
 
只看楼主 倒序阅读 楼主  发表于: 2007-11-06
— 本帖被 XChinux 从 General Qt Programming 移动到本区(2011-01-02) —
hi...all..
我想用elementsByTagName來得到xml中tagname是channel的node,
但是非常奇怪的是,它只會拿到一半的node,不知道是甚麼問題??
請各位幫我看看...

code如下
QDomDocument doc("test");
QDomDocument docTest("test"); //DomTest
QFile file("resource/test.xml"); //xml file locate in "resource" sub-folder...
    
  if (!file.open(QIODevice::ReadOnly))
        return "File is ReadOnly";
  if (!doc.setContent(&file)) {
      file.close();
      return "File is Invalid";
  }
file.close();

QDomElement docElem = doc.documentElement();
QDomNodeList aNodeList = doc.elementsByTagName("channel");
if(aNodeList.count()> 0){
    for(int i=0; i < aNodeList.count(); ++i ){
      e = aNodeList.at(i).toElement();
      docTest.appendChild(aNodeList.at(i));
  cout << qPrintable("Element Name:" + e.tagName() + "/" + e.attribute("id") ) << endl;   
    }
        QString NN;
        NN.setNum(aNodeList.length());
        cout<<qPrintable("Nodes Count:" + NN)<<endl;    
}

xml檔內容:
<tv>
<channel id="ATV"><display-name>ATV-Name</display-name></channel>
<channel id="BTV"><display-name>BTV-Name</display-name></channel>
<channel id="CTV"><display-name>CTV-Name</display-name></channel>
<channel id="DTV"><display-name>DTV-Name</display-name></channel>
<channel id="ETV"><display-name>ETV-Name</display-name></channel>
<channel id="FTV"><display-name>FTV-Name</display-name></channel>
<channel id="GTV"><display-name>GTV-Name</display-name></channel>
<channel id="HTV"><display-name>HTV-Name</display-name></channel>
</tv>

理論上NodeList.count()會是8,但是怎麼試都是4
cout出來發現只拿到ATV,CTV,ETV,GTV也就是單數的node.
這是怎麼回事呢??我哪裡有寫錯嗎???
麻煩各位幫我看看..
謝謝!

离线blf0
只看该作者 1楼 发表于: 2007-11-07
按照你的思路,我的打印结果是 8
我的代码如下:
#include <QtGui>
#include <QDomDocument>
#include <QDomElement>
#include <QDomNodeList>
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QDomDocument doc("xml");
    QFile file("books.xml");
    if(!file.open(QIODevice::ReadOnly)){
        QMessageBox::information(0,"can not open file","cant open");
        return 1;
    }
    doc.setContent(&file,true);
    QDomElement root = doc.documentElement();
    QDomNodeList nodeList = root.elementsByTagName("channel");
    QMessageBox::information(0,"",QString("%1").arg(nodeList.count()));
    return app.exec();
}

有的问题真是很难琢磨,昨天同学有个问题,列表的数据总是部分丢失,弄了半天问题是解决了,但仍觉得有点不可思议,觉得和内存有关,但也不敢肯定,所以你可以从程序的全局入手,查看一下,能做的只有这些了.
快速回复
限100 字节
 
上一个 下一个