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

本文介绍了如何使用Qt的DOM方法解析XML文件,并提供了详细的代码示例。从打开文件到解析DOM节点,再到提取所需信息的过程均有涉及。

       关于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;
复制代码
 

 

### Python 基础语法概述 Python 是一种解释型高级编程语言,以其简洁清晰的语法著称。对于初学者来说,理解其基本结构和语法规则是非常重要的。 #### 代码组织与缩进 Python 使用缩进来表示代码块之间的关系,而不是像其他一些编程语言那样使用大括号或其他分隔符。每一级缩进通常由四个空格组成[^2]。例如: ```python def my_function(): print("This is inside the function") # 这里有一个缩进级别 print("This line is outside of the function") ``` #### 控制流语句 Python 提供了几种常见的控制流工具来管理程序执行路径,包括条件判断 `if` 和循环 `for`, `while` 等。下面是一个简单的例子展示了如何使用这些语句: ```python number = 10 if number > 5: print(f"{number} is greater than five.") else: print(f"{number} is not greater than five.") for i in range(3): print(i) counter = 0 while counter < 3: print(counter) counter += 1 ``` #### 注释 为了提高代码可读性和维护性,在编写过程中添加适当注释是非常有益的做法。单行注释可以通过井号(`#`)实现;而多行注释则可以采用三重引号(无论是三个单引号还是双引号都可以)[^4]: ```python # This is a single-line comment. ''' This is a multi-line comment. It spans multiple lines. ''' """ Another way to write multi-line comments, using triple double quotes instead. """ ``` #### 变量定义 在 Python 中声明变量不需要指定数据类型,直接赋值即可创建新变量。支持多种内置的数据类型如整数(int), 浮点数(float),字符串(str)等: ```python integer_example = 42 # Integer variable floating_point_example = 3.14 # Float variable string_example = "Hello, world!" # String variable ``` 通过上述内容的学习,能够帮助建立起对 Python 编程的基础认识,并为进一步深入学习打下良好基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值