QT解析XML文件

1.打开储存XML

QString m_strFileName = "";

    m_strFileName = QFileDialog::getSaveFileName(this, tr("保存"),"/",tr("XML(*.xml)"),0,QFileDialog::DontUseNativeDialog);//打开文件

    if(m_strFileName.isEmpty())
    {
        return ;
    }
    if(!m_strFileName.endsWith(".xml"))
    {
        m_strFileName += ".xml";
    }
    QFile file(m_strFileName);
    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        return ;
    }

    QByteArray byteArray;
    QTextStream xml(&byteArray);
    xml.setCodec("UTF-8");
    QDomDocument doc;  //xml
    QDomElement dataElement = doc.createElement("data");//创建节点
    dataElement.setAttribute("ID","1");//节点赋予属性
    doc.appendChild(dataElement);//将节点放到xml下
    doc.save(xml,4,QDomNode::EncodingFromTextStream);
    file.write(byteArray);
    file.close();

2.打开解析XML

 QString m_strFileName = "";

    m_strFileName = QFileDialog::getOpenFileName(nullptr,"打开","/","Xml(*.xml)",0,QFileDialog::DontUseNativeDialog);
    if(m_strFileName.isEmpty()) return;

    QFile file(m_strFileName);//loadfileName
    if (!file.open(QFile::ReadWrite | QFile::Text))
    {
        return ;
    }

    QByteArray bytes = file.readAll();

    QDomDocument doc;
    if(!doc.setContent(bytes))
    {
        return ;
    }
    QDomElement dataElement = doc1.documentElement();//将XML根节点及下面的数据提取出来
    QDomNamedNodeMap map = dataElement.attributes();//获取节点属性
    for(int i = 0 ; i < map.length() ; ++i)
        {
         if(!(map.item(i).isNull()))
         {
          QDomNode debug = map.item(i);
          QDomAttr attr = debug.toAttr();
          if(!attr.isNull())
          {
           qDebug() << attr.name()<< attr.value();
          }
        }
    }
   QDomNodeList dataList = dataElement.childNodes();  //获取子节点

    for(int i=0;i

你可能感兴趣的:(xml,qt,ui)