QT读取xml有2个方法
对于xml数据比较大的就要用QXmlStreamReader
对于数据比较小的就用QDomDocument,这个比较方便
我这里就是以QDomDocument为主要内容,讲解如何读取
index.xml
[html] view plaincopyprint?
- <?xml version="1.0" encoding="utf-8"?>
- <ndex>
- <item>
- <id>1234567</id>
- <title>wangwang</title>
- <text>wuying</text>
- </item>
- <item>
- <id>1234567</id>
- <title>wangwang</title>
- <text>wuying</text>
- </item>
- <item>
- <id>1234567</id>
- <title>wangwang</title>
- <text>wuying</text>
- </item>
- </ndex>
main.cpp
[html] view plaincopyprint?
- #include <QtCore/QCoreApplication>
- #include "QFile"
- #include "QTextCodec"
- #include "QDomDocument"
- int main(int argc, char *argv[])
- {
- QTextCodec *codec = QTextCodec::codecForName("utf-8");
- QTextCodec::setCodecForLocale(codec);
- QTextCodec::setCodecForCStrings(codec);
- QTextCodec::setCodecForTr(codec);
- QCoreApplication a(argc, argv);
- QDomDocument doc;
- QFile xmlfile("index.xml"); //filepath为xml文件路径
- if (!xmlfile.open(QIODevice::ReadOnly))
- {
- return false;
- }
- if (!doc.setContent(&xmlfile))
- {
- xmlfile.close();
- return false;
- }
- QDomElement root = doc.documentElement();
- QDomNode node=root.firstChild().firstChild().nextSibling();
- qDebug(node.toElement().text().toAscii());
- qDebug(node.nodeName().toAscii());
- return a.exec();
- }
时间: 2024-10-14 06:20:06