qt xml读取attribute
时间: 2024-05-16 10:18:11 浏览: 10
在 Qt 中,可以使用 QDomElement 类来读取 XML 元素的属性。假设我们有以下的 XML 文件:
```xml
<book id="1">
<title>Qt5 Programming</title>
<author>Jason Yang</author>
<publisher>Packt Publishing</publisher>
</book>
```
我们可以使用以下代码来读取 `book` 元素的 `id` 属性:
```cpp
#include <QFile>
#include <QtXml>
int main()
{
QFile file("book.xml");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
QDomDocument doc;
if (!doc.setContent(&file)) {
file.close();
return -1;
}
file.close();
QDomElement root = doc.documentElement();
QDomElement book = root.firstChildElement("book");
QString id = book.attribute("id");
qDebug() << "Book ID:" << id;
return 0;
}
```
在上面的代码中,我们首先打开 XML 文件并将其解析为 QDomDocument 对象。然后,我们获取根元素和第一个 `book` 元素,并通过 `attribute` 函数获取 `id` 属性的值。最后,我们使用 qDebug 输出 `id` 的值。