目录
创建xml
//文件路径
QString xmlPath = "G:/1.xml";
QFile file(xmlPath);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
//实例 QXmlStreamWriter
QXmlStreamWriter stream(&file);
stream.setAutoFormatting(true);
//文档头
stream.writeStartDocument();
//根节点
stream.writeStartElement("Root");
//元素、值
stream.writeAttribute("href", "http://qt.nokia.com/");
//节点内容
stream.writeTextElement("title", "Qt Home");
stream.writeEndElement();
stream.writeEndDocument();
//关闭文件
file.close();
}
读取xml
QString xmlPath = "G:/1.xml";
QFile file(xmlPath);
//定义变量接收信息
QString str;
//判断文件是否存在
if(file.exists())
{
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
//实例 QXmlStreamReader 对象读取文件
QXmlStreamReader xmlRead(&file);
//循环节点
while (!xmlRead.atEnd())
{
//指针下移
xmlRead.readNext();
if(xmlRead.isStartElement())
{
//如果节点有等于 title 的
if(xmlRead.name() == "title")
{
//取 title 值赋予变量 str
str = xmlRead.readElementText();
qDebug()<<str;
}
else
{
str = "没找到节点";
}
}
}
}
else
{
qDebug()<<"文件打开失败";
}
//关闭文件
file.close();
}
else
{
qDebug()<<"文件不存在";
}