qt -- 创建和读取xml文件

目录

创建xml

 读取xml


创建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()<<"文件不存在";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值