QDomDocument 使用示例
时间: 2023-06-23 08:09:09 浏览: 56
QDomDocument 是 Qt 框架中用于处理 XML 文档的类,以下是一个简单的使用示例:
```cpp
#include <QDomDocument>
#include <QFile>
#include <QDebug>
int main()
{
// 创建一个空的 QDomDocument 对象
QDomDocument doc;
// 创建根元素
QDomElement root = doc.createElement("root");
doc.appendChild(root);
// 创建子元素
QDomElement child1 = doc.createElement("child1");
child1.setAttribute("name", "Alice");
root.appendChild(child1);
QDomElement child2 = doc.createElement("child2");
child2.setAttribute("name", "Bob");
root.appendChild(child2);
// 保存到文件
QFile file("example.xml");
if (file.open(QIODevice::WriteOnly))
{
QTextStream out(&file);
doc.save(out, 4);
file.close();
}
// 从文件读取并解析 XML
if (file.open(QIODevice::ReadOnly))
{
if (doc.setContent(&file))
{
QDomNodeList children = doc.documentElement().childNodes();
for (int i = 0; i < children.count(); i++)
{
QDomNode child = children.at(i);
if (child.isElement())
{
QDomElement element = child.toElement();
QString name = element.tagName();
QString value = element.attribute("name");
qDebug() << "Element: " << name << ", Attribute: " << value;
}
}
}
file.close();
}
return 0;
}
```
这个示例中,我们首先创建了一个空的 QDomDocument 对象,然后创建了一个根元素和两个子元素,并将它们添加到文档中。接着,我们将文档保存到文件 example.xml 中,然后从文件中读取并解析 XML,输出每个元素的名称和属性值。输出结果如下:
```
Element: child1 , Attribute: Alice
Element: child2 , Attribute: Bob
```
以上就是 QDomDocument 的一个简单使用示例。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)