qdomdocument解析xml文件 代码
时间: 2024-02-29 14:52:02 浏览: 72
QDomDocument是Qt中用于解析和创建XML文档的类。以下是一个简单的示例代码,演示如何使用QDomDocument类解析XML文件:
```cpp
#include <QFile>
#include <QtXml>
int main()
{
QFile file("example.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
QDomDocument doc;
if (!doc.setContent(&file))
{
file.close();
return -1;
}
QDomElement root = doc.documentElement();
QDomNodeList books = root.elementsByTagName("book");
for (int i = 0; i < books.count(); i++)
{
QDomNode book = books.at(i);
if (book.isElement())
{
QDomElement elem = book.toElement();
QString title = elem.attribute("title");
QString author = elem.attribute("author");
qDebug() << "Title: " << title << "Author: " << author;
}
}
file.close();
return 0;
}
```
在这个示例中,我们打开一个名为"example.xml"的文件,然后使用QDomDocument类将其内容读入到内存中。接下来,我们获取XML文档的根元素,然后遍历其子元素中所有名为"book"的元素,并从中获取"title"和"author"属性。最后,我们关闭文件并返回。
请注意,QDomDocument类是基于DOM模型的解析器,它会将整个XML文档加载到内存中,因此适用于较小的XML文档。如果XML文档非常大,建议使用SAX模型的解析器,如QXmlStreamReader类。
阅读全文
相关推荐

















