Fork me on GitHub

初识---Qt解析XML文件(QDomDocument)

       关于XML及其使用场景不在此多做介绍,今天主要介绍Qt中对于XML的解析。QtXml模块提供了一个读写XML文件的流,解析方法包含DOM和SAX,两者的区别是什么呢?  DOM(Document Object Model):将XML文件保存为树的形式,操作简单,便于访问。SAX(Simple API for XML):接近于底层,速度较快,但不便于访问。

建议阅读:http://www.devbean.net/2013/08/qt-study-road-2-read-xml-with-dom/  这篇博客,最好做一下试验!

因为下vs2013下开发Qt有些库需要手动添加!!!QXml,QSql,,

一般出现这个问题都是库文件没有添加造成,这里使用QtNetwork就要加QtNetwork的库文件,在debug模式下需要加Qt5Networkd.lib库文件,在release模式下需要加QtNetwork5.lib库文件在哪里添加呢,一共有两个地方需要添加,缺一不可

1. 项目->属性->c/c++->常规->附加包含目录->在弹出的对话框中,点那个文件夹形状的按钮添加新行,输入$(QTDIR)\include\QtNetwork

2. 项目->属性->连接器->输入->附加依赖项,添加 Qt5Networkd.lib(debug模式)或者 Qt5Network.lib(release模式)

 
person.xml文件如下所示:
Qt解析XML文件(QDomDocument)
解析方法:
void ParseXML::parse(QString file_name)  
{  
    if(file_name.isEmpty())  
        return;  
  
    QFile file(file_name);  
    if(!file.open(QFile::ReadOnly | QFile::Text))
    {  
        QMessageBox::information(NULL, QString("title"), QString("open error!"));
 
        return;  
    }  
  
    QDomDocument document;  
    QString error;  
    int row = 0, column = 0;  
    if(!document.setContent(&file, false, &error, &row, &column))
    {  
        QMessageBox::information(NULL, QString("title"), QString("parse file failed at line row and column") + QString::number(row, 10) + QString(",") + QString::number(column, 10));
 
        return;  
    }  
  
    if(document.isNull())
    {  
        QMessageBox::information(NULL, QString("title"), QString("document is null!"));
        
        return;  
    }  
  
    QDomElement root = document.documentElement();  
 
    //root_tag_name为persons
    QString root_tag_name = root.tagName();
    if(root.hasAttribute("name"))
    {
        //name为Qt
        QString name = root.attributeNode("name").value(); 
    }
       
    //获取id="1"的节点
    QDomElement person = root.firstChildElement();  
    if(person.isNull()) 
        return; 
 
    QString person_tag_name = person.tagName();
 
    //id为1
    QString id = person.attributeNode("id").value();
 
    //获取子节点,数目为2
    QDomNodeList list = root.childNodes();
    int count = list.count();
    for(int i=0; i
    {
        QDomNode dom_node = list.item(i);
        QDomElement element = dom_node.toElement();
 
        //获取id值,等价
        QString id_1 = element.attributeNode("id").value(); 
        QString id_2 = element.attribute("id");
 
        //获取子节点,数目为4,包括:name、age、email、website
        QDomNodeList child_list = element.childNodes();
        int child_count = child_list.count();
        for(int j=0; j
        {
            QDomNode child_dom_node = child_list.item(j);
            QDomElement child_element = child_dom_node.toElement();
            QString child_tag_name = child_element.tagName();
            QString child__tag_value = child_element.text();
        }
    }
 
    //按照name、age、email、website的顺序获取值
    QDomElement element = person.firstChildElement();  
    while(!element.isNull())
    {  
        QString tag_name = element.tagName();
        QString tag_value = element.text();
        element = element.nextSiblingElement();  
    }  
}  

XML文件如下所示:

<?xml version="1.0" encoding="GBK"?>
<Catalog name = "树形目录">
        <View id = "default">
                <任务年度/>
                <任务编号/>
                <任务名称/>
    </View>
        <View id = "1">
                <任务名称/>
                <任务年度/>
                <任务编号/>
    </View>
        <View id = "2">
                <任务年度/>
                <任务名称/>
                <任务编号/>
        </View>
</Catalog>

  读文件:

if("" == fileName)
    {
        qDebug()<<"Filename is Null";
        return;
    }
    QFile file(DirectorOf("xml").absoluteFilePath(fileName));
    if(!file.open(QFile::ReadOnly | QFile::Text))
        qDebug()<<"open file"<<fileName<<"failed, error:"<<file.errorString();
    /*解析Dom节点*/
       QDomDocument    document;
       QString         strError;
       int             errLin = 0, errCol = 0;
       if( !document.setContent(&file, false, &strError, &errLin, &errCol) ) {
           qDebug()<<"parse file failed at line"<<errLin<<",column"<<errCol<<","<<strError;
           return;
       }
 
       if( document.isNull() ) {
           qDebug()<<"document is null !";
           return;
       }
 
       QDomElement root = document.documentElement();
       qDebug()<<root.tagName();
 
       QDomElement catalogs = root.firstChildElement();
       if( catalogs.isNull() )
           return;
       else
           qDebug()<<catalogs.tagName();
       while(!catalogs.isNull())
       {
           QString tag = catalogs.attributeNode("id").value();
           QStringList child;
           QPair<QString,QStringList> pair;
           for(int i = 0;i < catalogs.childNodes().size();i++)
               child<<catalogs.childNodes().at(i).nodeName();
           pair.first = tag;
           pair.second = child;
           catalogList.append(pair);
           catalogs = catalogs.nextSiblingElement();
       }
       file.close();

 

写入XML

复制代码
QFile file(DirectorOf("xml").absoluteFilePath(xmlName));
       if (!file.open(QFile::ReadOnly | QFile::Text))
             return false;
       QString errorStr;
       int errorLine;
       int errorColumn;
       QDomDocument doc;
       if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn))
            return false;
       file.close();
       QDomElement root = doc.documentElement();
       if(root.tagName() != "Catalog")
           return false;
       QDomElement element =  doc.createElement("View");
       QDomAttr idAttr = doc.createAttribute("id");
       element.setAttributeNode(idAttr);
       element.setAttribute("id",typeName);
       for(int i = 0;i < catalogs.size();i++)
       {
           QDomElement cataItem = doc.createElement(catalogs.at(i));
           element.appendChild(cataItem);
       }
       root.appendChild(element);
      /* QDomProcessingInstruction instruction;
       instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"GBK\"");
       doc.appendChild(instruction);*/
       QFile f(DirectorOf("xml").absoluteFilePath(xmlName));
           if(!f.open(QFile::WriteOnly | QFile::Text))
               return false;
       QTextStream out(&f);
       doc.save(out,4);
       f.close();
       return true;
复制代码
 

 

posted @ 2016-03-30 16:24  ranjiewen  阅读(10048)  评论(0编辑  收藏  举报