#include <QtCore/QCoreApplication>
#include <QTextCodec>
#include <QtXml>
int main(int argc, char *argv[])
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QCoreApplication a(argc, argv);
QDomDocument doc; //新建QDomDocument类对象,它代表一个XML文档
QFile file("test.xml"); //建立指向test.xml文件的QFile对象
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "file open readonly!";
return 0; //以只读方式打开
}
//将文件内容读到doc中
if (!doc.setContent(&file))
{
qDebug() << "doc setContent!";
file.close();
return 0;
}
file.close(); //关闭文件
QDomNode firstNode = doc.firstChild(); //获得doc的第一个节点,即XML说明
qDebug() << qPrintable(firstNode.nodeName()) << qPrintable(firstNode.nodeValue()); //输出XML说明
//qDebug() << qPrintable(firstNode.nodeName());
QDomElement docElem = doc.documentElement(); //返回根元素
QDomNode n = docElem.firstChild(); //返回根节点的第一个子节点
while(!n.isNull())
{
if (n.isElement()) //如果节点是元素
{
QDomElement e = n.toElement(); //将其转换为元素
//qDebug() << qPrintable(e.tagName()) << qPrintable(e.attribute("id")); //返回元素id属性的值 //返回元素标记
qDebug() << qPrintable(e.tagName()); //返回元素id属性的值 //返回元素标记
QDomNodeList list = e.childNodes(); //获得元素e的所有子节点的列表
for(int i=0; i<list.count(); i++) //遍历该列表
{
QDomNode node = list.at(i);
if(node.isElement())
{
if(node.toElement().tagName() == "item")
{
QDomNodeList p = list.at(i).childNodes();
for(int j=0; j<p.count(); j++)
{
QDomNode pnode = p.at(j);
if(pnode.isElement())
qDebug() << " " << qPrintable(pnode.toElement().tagName()) << qPrintable(pnode.toElement().text());
}
}
else
qDebug() << " " << qPrintable(node.toElement().tagName()) << qPrintable(node.toElement().text());
}
//if(node.isElement())
// qDebug() << " " << qPrintable(node.toElement().tagName()) << qPrintable(node.toElement().text());
}
}
n = n.nextSibling();
}
return a.exec();
}
Qt读xml的一个简单实例
5星 · 超过95%的资源 需积分: 50 4 浏览量
2011-12-13
13:23:09
上传
评论
收藏 249KB ZIP 举报
卧龙居
- 粉丝: 2
- 资源: 15
最新资源
- ### 词向量的介绍、使用技巧和优缺点的文章
- 基于STM32F103CBT6单片机GC65+MP2625+CC1101 GPSTrack模块板硬件(原理图+PCB)工程文件
- ### 通道处理过程模拟概念、优缺点和使用技巧
- ### MyBatis动态SQL介绍说明、使用技巧和优缺点
- 上传下载仿163网盘无刷新文件上传 for Jsp-fileupload-jsp.rar
- VMware Workstation业界非常稳定且安全的桌面虚拟机软件-计算机上运行多个操作系统,支持Windows、DOS等
- 基于STM8L101F3P6单片机+LY2508A33P+CC1100遥控器硬件(原理图+PCB)工程文件.zip
- 上传下载WAP图铃下载系统-unimg.rar
- YTX-0.1.0-Win
- 上传下载ExtJS 2.2 开源网络硬盘系统-dogdisk.rar
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
前往页