QT 對XML 文件進行增刪改查


xml文件本身也是一種文本文件

如下:

<?xml version='1.0' encoding='UTF-8'?>
<library>
    <book id="1" time="2013/6/13">
        <title>C++ primer</title>
        <author>Stanley Lippman</author>
    </book>
    <book id="3" time="1813/1/27">
        <title>Emma</title>
        <author>Jane Austen</author>
    </book>
</library>

首先寫入的xml文件要確定xml文件的格式

格式:1、寫入xml的頭部 <?xml version='1.0' encoding='UTF-8'?>

   2、添加最外層的根(root)節點,如示例<library></library> QDomElement

   3、添加根節點的第一個節點以及元素 如示例 <book id="1" time="2013/6/13">

      節點為<book></book> 節點內容為id="1" time="2013/6/13"

   4、添加根節點的元素,元素又為節點<title></title>;<author></author>

寫xml如下:

 

void WriteXml()
{
    //打開或創建文件
    QFile file("E:/QT_STUDY_HEIMA/qt_xml_test.xml"); //相對路徑、絕對路徑、資源路徑都可以
    if(!file.open(QFile::WriteOnly|QFile::Truncate)) //可以用QIODevice,Truncate表示清空原來的內容
        return;

    QDomDocument doc;
    //寫入xml頭部
    QDomProcessingInstruction instruction; //添加處理命令
    instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
    doc.appendChild(instruction);
    //添加根節點
    QDomElement root=doc.createElement("library");
    doc.appendChild(root);
    //添加第一個子節點及其子元素
    QDomElement book=doc.createElement("book");
    book.setAttribute("id",1); //方式一:創建屬性  其中鍵值對的值可以是各種類型
    QDomAttr time=doc.createAttribute("time"); //方式二:創建屬性 值必須是字符串
    time.setValue("2013/6/13");
    book.setAttributeNode(time);
    QDomElement title=doc.createElement("title"); //創建子元素
    QDomText text; //設置括號標簽中間的值
    text=doc.createTextNode("C++ primer");
    book.appendChild(title);
    title.appendChild(text);
    QDomElement author=doc.createElement("author"); //創建子元素
    text=doc.createTextNode("Stanley Lippman");
    author.appendChild(text);
    book.appendChild(author);
    root.appendChild(book);

    //添加第二個子節點及其子元素,部分變量只需重新賦值
    book=doc.createElement("book");
    book.setAttribute("id",2);
    time=doc.createAttribute("time");
    time.setValue("2007/5/25");
    book.setAttributeNode(time);
    title=doc.createElement("title");
    text=doc.createTextNode("Thinking in Java");
    book.appendChild(title);
    title.appendChild(text);
    author=doc.createElement("author");
    text=doc.createTextNode("Bruce Eckel");
    author.appendChild(text);
    book.appendChild(author);
    root.appendChild(book);

    //輸出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //縮進4格
    file.close();

}

 

讀xml

  1、打開文件

  2、使用documentElement 獲取根節點

  3、 QDomNode node可以獲得第一個子節點

    4、對子節點進行判斷,判斷是否為空,不為空則進行判斷節點是否為元素,如果節點是元素,需要將元素中的節點轉換成元素,並將其    子元素的節點元素放到鏈表,進行循環判斷鏈表輸出元素;遍歷完節點元素后,進行遍歷鄰居節點

讀xml

 

//讀xml
void ReadXml()
{
    //打開或創建文件
    QFile file("E:/QT_STUDY_HEIMA/qt_xml_test.xml"); //相對路徑、絕對路徑、資源路徑都行
    if(!file.open(QFile::ReadOnly))
        return;

    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();

    QDomElement root=doc.documentElement(); //返回根節點
    qDebug()<<root.nodeName();
    QDomNode node=root.firstChild(); //獲得第一個子節點
    while(!node.isNull())  //如果節點不空
    {
        if(node.isElement()) //如果節點是元素
        {
            QDomElement e=node.toElement(); //轉換為元素,注意元素和節點是兩個數據結構,其實差不多


            qDebug()<<e.tagName()<<" "<<e.attribute("id")<<" "<<e.attribute("time"); //打印鍵值對,tagName和nodeName是一個東西
            QDomNodeList list=e.childNodes();
            for(int i=0;i<list.count();i++) //遍歷子元素,count和size都可以用,可用於標簽數計數
            {
                QDomNode n=list.at(i);
                if(node.isElement())
                    qDebug()<<n.nodeName()<<":"<<n.toElement().text();
            }
        }
        node=node.nextSibling(); //下一個兄弟節點,nextSiblingElement()是下一個兄弟元素,都差不多
    }

}

 

增加xml

 1、增加方式與寫xml方式一樣,只需要注意追加內容的方式QFile::Truncate就可以了

增加xml

//增加xml內容
void AddXml()
{
    //打開文件
    QFile file("E:/QT_STUDY_HEIMA/qt_xml_test.xml"); //相對路徑、絕對路徑、資源路徑都可以
    if(!file.open(QFile::ReadOnly))
        return;

    //增加一個一級子節點以及元素
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();

    QDomElement root=doc.documentElement();
    QDomElement book=doc.createElement("book");
    book.setAttribute("id",3);
    book.setAttribute("time","1813/1/27");
    QDomElement title=doc.createElement("title");
    QDomText text;
    text=doc.createTextNode("Pride and Prejudice");
    title.appendChild(text);
    book.appendChild(title);
    QDomElement author=doc.createElement("author");
    text=doc.createTextNode("Jane Austen");
    author.appendChild(text);
    book.appendChild(author);
    root.appendChild(book);

    if(!file.open(QFile::WriteOnly|QFile::Truncate)) //先讀進來,再重寫,如果不用truncate就是在后面追加內容,就無效了
        return;
    //輸出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //縮進4格
    file.close();
}

刪除xml

  1、需要根據標簽為去定位刪除的內容,在根據屬性名定位

刪除xml

//刪減xml內容
void RemoveXml()
{
    //打開文件
    QFile file("E:/QT_STUDY_HEIMA/qt_xml_test.xml"); //相對路徑、絕對路徑、資源路徑都可以
    if(!file.open(QFile::ReadOnly))
        return;

    //刪除一個一級子節點及其元素,外層節點刪除內層節點於此相同
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();  //一定要記得關掉啊,不然無法完成操作

    QDomElement root=doc.documentElement();
    QDomNodeList list=doc.elementsByTagName("book"); //由標簽名定位
    for(int i=0;i<list.count();i++)
    {
        QDomElement e=list.at(i).toElement();
        if(e.attribute("time")=="2007/5/25")  //以屬性名定位,類似於hash的方式,warning:這里僅僅刪除一個節點,其實可以加個break
            root.removeChild(list.at(i));
    }

    if(!file.open(QFile::WriteOnly|QFile::Truncate))
        return;
    //輸出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //縮進4格
    file.close();
}

更新xml

//更新xml內容
void UpdateXml()
{
    //打開文件
    QFile file("E:/QT_STUDY_HEIMA/qt_xml_test.xml"); //相對路徑、絕對路徑、資源路徑都可以
    if(!file.open(QFile::ReadOnly))
        return;

    //更新一個標簽項,如果知道xml的結構,直接定位到那個標簽上定點更新
    //或者用遍歷的方法去匹配tagname或者attribut,value來更新
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();

    QDomElement root=doc.documentElement();
    QDomNodeList list=root.elementsByTagName("book");
    QDomNode node=list.at(list.size()-1).firstChild(); //定位到第三個一級子節點的子元素
    QDomNode oldnode=node.firstChild(); //標簽之間的內容作為節點的子節點出現,當前是Pride and Projudice
    node.firstChild().setNodeValue("Emma");
    QDomNode newnode=node.firstChild();
    node.replaceChild(newnode,oldnode);

    if(!file.open(QFile::WriteOnly|QFile::Truncate))
        return;
    //輸出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //縮進4格
    file.close();
}

主函數mian

int main(int argc, char *argv[])
{

    qDebug()<<"write xml to file...";
    WriteXml();
    qDebug()<<"read xml to display...";
    ReadXml();
    qDebug()<<"add contents to xml...";
    AddXml();
    qDebug()<<"remove contents from xml...";
    RemoveXml();
    qDebug()<<"update contents to xml...";
    UpdateXml();
    return 0;

}

參考鏈接:https://blog.csdn.net/hpu11/article/details/80227093

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM