xml例子,自己总是忘记 写下来记录下
<UavData root="data">
<Item0 d="10000" a="99" b="44" b="2000"/>
<Item1 d="10000" a="99" b="44" c="2000"/>
</UavData>
1.创建文件
QString filename = "my.xml";
if (!QFile::exists(filename)) {
// 如果文件不存在,则创建新文件
QFile newFile(filename);
if (newFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug() << u8"文件不存在,已创建新文件:" << filename;
newFile.close();
} else {
qDebug() << u8"文件已存在,无法创建新文件:" << filename;
}
}
2.尝试加载xml文件(读取此文章提到过得xml)
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "无法打开文件进行读取";
return;
}
QXmlStreamReader xmlReader(&file);// 创建XML读取器并传入文件对象
while (!xmlReader.atEnd() && !xmlReader.hasError())//当结束或者出错是退出
{
QXmlStreamReader::TokenType token = xmlReader.readNext();// 读取下一个XML标记
if (token == QXmlStreamReader::StartDocument)
{
continue;
}
if (token == QXmlStreamReader::StartElement)
{
if (xmlReader.name() == "UavData" && xmlReader.attributes().hasAttribute("root"))
{
qDebug() << "Root element: " << xmlReader.attributes().value("root").toString();
}
else if (xmlReader.name().toString().startsWith("Item"))//判断节点名称是否包含item的字符串
{
QXmlStreamAttributes attributes = xmlReader.attributes();
QString str = attributes.value("a").toString()
}
}
}
3.尝试写入数据到xml
这里的waypoints是我自己创建的一个map容器 所以随便改什么值都可以 xml内的数据反正是对应的
QFile file(filePath);
int indexItem = 0;
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
QDomDocument doc;
// 创建根元素
QDomElement root = doc.createElement("UavData");
root.setAttribute("root", "data");
doc.appendChild(root);
for(auto item : waypoints)
{
//get子元素赋值
// 创建子元素 Item1
QDomElement item1 = doc.createElement("Item" + QString::number(indexItem++));
item1.setAttribute("a", item.second.a);
item1.setAttribute("b", item.second.b);
item1.setAttribute("c", item.second.c);
item1.setAttribute("d", item.second.d);
root.appendChild(item1);//添加到root根节点下
}
// 关闭文件
file.close();
// 保存 XML 到文件
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&file);
stream << doc.toString();
file.close();
qDebug() << u8"XML 文件已写入";
}
else
{
qDebug() << "无法打开文件进行写入";
}
}