QT5.2 QDomDocument操作xml

#include <QCoreApplication>
#include <QtXml>
#include <QFile>
#include <qDebug>

void writeXml();
void readxml();


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qDebug()<<"write xml to file ... ...";
    writeXml();
    readxml();
    return a.exec();
}

void writeXml()
{
    QFile file("/xmltest/test.xml");
    if(!file.exists())
        qDebug()<<"file not exists";

    if( !file.open(QFile::WriteOnly|QFile::Truncate))
        qDebug()<<"open fail!!"<<endl;

    //写xml
    QDomDocument doc;
    QDomProcessingInstruction 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("2019/02/11");
    book.setAttributeNode(time);
    QDomElement title = doc.createElement("title");
    QDomText text;
    text = doc.createTextNode("Qt");
    book.appendChild(title);
    title.appendChild(text);

    QDomElement author=doc.createElement("author");
    text=doc.createTextNode("muchuxni");
    author.appendChild(text);
    book.appendChild(author);
    root.appendChild(book);

    QTextStream outstream(&file);
    doc.save(outstream,4);
    outstream.flush();
    file.close();
    qDebug()<<"closed";

}

void readxml()
{
    QFile file("/xmltest/test.xml");
    if(!file.open(QFile::ReadOnly))
        qDebug()<<"open fail";
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        file.close();
        return;
    }
    file.close();

    QDomElement root = doc.documentElement();
    qDebug()<<root.nodeName()<<root.nodeType();
    QDomNode node=root.firstChild();//获取跌一个子节点
    while(!node.isNull())
    {
        if(node.isElement())
        {
            QDomElement e=node.toElement();
            qDebug()<<e.tagName();
            QDomNodeList list=e.childNodes();
            for(int i=0; i<list.count(); i++)
            {
                QDomNode n=list.at(i);
                if(node.isElement())
                    qDebug()<<n.nodeName()<<":"<<n.toElement().text();
            }
        }
        node=node.nextSibling();
    }
}

发布了27 篇原创文章 · 获赞 19 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/muaxi8/article/details/104264425