Qt学习之路——XML Editor

September 22nd, 2013 by JasonLe's Tech Leave a reply »

接着刚才的Write XML来写。。。。。
这个Editor有界面,我使用MVC的方式,插入数据都通过QStandardItem来插入,这个model都是tree view,通过QDomDocument里面的setContent()方法导入。然后就是通过firstChildElement来找到root节点,然后开始下面的工作。
XML数据与上一节内容相同,这里不再赘述。

XML读写流程 QDomElement -> QDomNodeList -> toElement ->…..

QDomElement xmlroot = document.firstChildElement();
QDomNodeList books = xmlroot.elementsByTagName("Book");
QDomElement book = books.at(i).toElement();
QDomNodeList chapters = book.elementsByTagName("Chapter");
QDomElement chapter = chapters.at(h).toElement();

其实感觉tree view model插入方式和QDomDocument方式很类似,都是要找到root节点,才能向后插入
model层级关系:root->bookitem->chapteritem

void Dialog::ReadFile()
{
    QStandardItem *root = new QStandardItem("Books");
    model->appendRow(root);

    QDomDocument document;
    QFile file(FileName);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        document.setContent(&file);
        file.close();
    }

    QDomElement xmlroot = document.firstChildElement();

    QDomNodeList books = xmlroot.elementsByTagName("Book");//通过root我找到child节点Book

    for(int i =0;i<books.count();i++)
    {
        QDomElement book = books.at(i).toElement();
        QStandardItem *bookitem = new QStandardItem(book.attribute("Name"));

        QDomNodeList chapters = book.elementsByTagName("Chapter");
        for(int h= 0;h<chapters.count();h++)
        {
            QDomElement chapter = chapters.at(h).toElement();
            QStandardItem *chapteritem = new QStandardItem(chapter.attribute("Name"));
            bookitem->appendRow(chapteritem);
        }
        root->appendRow(bookitem);

    }
}

void Dialog::WriteFIle()
//写的原理和读其实很类似,,他是从model中获取item而已,然后回复这个xml节点信息。
{

    QDomDocument document ;

    QDomElement xmlroot = document.createElement("Books");
    document.appendChild(xmlroot);

    QStandardItem *root = model->item(0,0);
    for(int i= 0;i < root->rowCount();i++)
    {
        QStandardItem *book = root->child(i,0);

        QDomElement xmlbook = document.createElement("Book");
        xmlroot.appendChild(xmlbook);

        xmlbook.setAttribute("Name",book->text());
        xmlbook.setAttribute("ID",i);


        for(int h =0 ;h< book->rowCount();h++)
        {
            QStandardItem *chapter = book->child(h,0);
            QDomElement xmlchapter = document.createElement("Chapter");
            xmlchapter.setAttribute("Name",chapter->text());
            xmlchapter.setAttribute("ID",h);
            xmlbook.appendChild(xmlchapter);
        }
    }

//    QFile file(FileName);
    QFile file("/home/lzz/test.xml");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug() << "Failed to write file";
    }
    QTextStream stream(&file);
    stream << document.toString();
    file.close();


    qDebug() << "Finished!!!";
}

2013-09-22 21:26:36的屏幕截图