使用Qt生成XML文件的步骤如下:
包含头文件:
#include <QDomDocument>
创建一个QDomDocument对象:
QDomDocument doc;
创建根节点:
QDomElement root = doc.createElement("root");
将根节点添加到文档中:
doc.appendChild(root);
创建子节点并设置属性和文本内容:
QDomElement child = doc.createElement("child");
child.setAttribute("id", "1");
child.appendChild(doc.createTextNode("Hello World"));
将子节点添加到根节点中:
root.appendChild(child);
保存文档到文件:
doc.save("file.xml", 4);
完整代码示例:
#include <QCoreApplication>
#include <QDomDocument>
#include <QFile>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建文档
QDomDocument doc;
// 创建根节点
QDomElement root = doc.createElement("root");
// 添加根节点到文档中
doc.appendChild(root);
// 创建子节点并设置属性和文本内容
QDomElement child = doc.createElement("child");
child.setAttribute("id", "1");
child.appendChild(doc.createTextNode("Hello World"));
// 将子节点添加到根节点中
root.appendChild(child);
// 保存文档到文件
QFile file("file.xml");
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&file);
stream << doc.toString(4);
file.close();
}
return a.exec();
}
运行程序后,将生成一个名为file.xml的文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child id="1">Hello World</child>
</root>