[QT操作XML]QT读写XML文件,QT修改XML文件

XML简介

概念:Extensible Markup Language 可扩展标记语言(可扩展:标签都是自定义的)
功能:存储数据(1. 配置文件、2. 在网络中传输)
XML基本语法:
1. xml文档的后缀名 .xml
2. xml第一行必须定义为文档声明
3. xml文档中有且仅有一个根标签
4. 属性值必须使用引号(单双都可)引起来
5. 标签必须正确关闭
6. xml标签名称区分大小写
文档声明格式:<?xml version='1.0' encoding='UTF-8'?>
version:版本号,必须的属性
encoding:编码方式,告知解析引擎当前文档使用的字符集编码方式,默认值:ISO-8859-1
standalone:是否独立(取值,yes:不依赖其他文件;no:依赖其他文件)

QT操作XML,写入、读取、修改

pro文件增加xml模块:QT += xml
包含头文件:#include

//写入XML
void MainWindow::writeXML()
{
    QFile file("test.xml");//打开或新建xml文件
    if(!file.open(QIODevice::WriteOnly|QIODevice::Truncate))//Truncate表示清空原来的内容
    {
        QMessageBox::warning(this,"错误","文件打开失败");
        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);//方法1,创建属性,键值对可以是各种类型
    QDomAttr time = doc.createAttribute("time");//方法2,创建属性,值必须是字符串
    time.setValue("2020/6/3");
    book.setAttributeNode(time);

    QDomElement title = doc.createElement("title");//创建子元素
    QDomText text = doc.createTextNode("C++ primer");//设置括号标签中间的值
    book.appendChild(title);
    title.appendChild(text);
    QDomElement author = doc.createElement("author");//创建子元素
    text = doc.createTextNode("Stanley B.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文件
void MainWindow::readXML()
{
    QFile file("test.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"错误","读XML,文件打开失败");
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))//从字节数组中解析XML文档,并将其设置为文档的内容
    {
        file.close();
        return;
    }
    file.close();
    QDomElement root = doc.documentElement();//返回根节点
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"root.nodeName "<<root.nodeName();//打印根节点
    QDomNode node = root.firstChild();//获得第一个子节点
    while(!node.isNull())//如果节点不为空
    {
        if(node.isElement())//如果节点是元素
        {
            QDomElement e= node.toElement();//节点转换为元素
            //打印键值对,tagName和nodeName相同
            qDebug() << e.tagName()<< " " <<e.attribute("id")<<" "<<e.attribute("time");
            QDomNodeList list = e.childNodes();//子节点列表
            for(int i=0;i<list.count();i++)//遍历子节点
            {
                QDomNode n = list.at(i);
                if(n.isElement())
                    qDebug() << n.nodeName()<<":"<<n.toElement().text();
            }
        }
        node=node.nextSibling();//下一个兄弟节点
    }
}

//增加XML内容
//先把文件读进来,再重写
void MainWindow::addXML()
{
    QFile file("test.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"错误","增加XML,文件打开失败1");
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))//从字节数组中解析XML文档,并将其设置为文档的内容
    {
        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就是在后面追加内容,就无效了
    {
        QMessageBox::warning(this,"错误","增加XML,文件打开失败2");
        return;
    }
    QTextStream out_stream(&file);
    doc.save(out_stream,4);
    file.close();
}

//删减XML内容
void MainWindow::removeXML()
{
    QFile file("test.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"错误","增加XML,文件打开失败1");
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))//从字节数组中解析XML文档,并将其设置为文档的内容
    {
        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")
            root.removeChild(list.at(i));
    }
    if(!file.open(QFile::WriteOnly|QFile::Truncate))//重写文件,如果不用truncate就是在后面追加内容,就无效了
    {
        QMessageBox::warning(this,"错误","删减XML内容,文件打开失败");
        return;
    }
    QTextStream out_stream(&file);
    doc.save(out_stream,4);
    file.close();
}

//更新XML内容
//如果了解XML结构,可以直接定位到指定标签上更新
//或者用遍历的方法去匹配tagname或者attribut,value来更新
void MainWindow::updateXML()
{
    QFile file("test.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(this,"错误","更新XML,文件打开失败1");
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))//从字节数组中解析XML文档,并将其设置为文档的内容
    {
        file.close();
        return;
    }
    file.close();

    QDomElement root = doc.documentElement();//获得根节点
    QDomNodeList list = root.elementsByTagName("book");//指定名称的节点列表
    QDomNode node = list.at(list.count()-1).firstChild();//定位到第三个一级子节点的子元素
    QDomNode oldNode = node.firstChild();//标签之间的内容作为节点的子节点出现,当前是Pride and Projudice
    oldNode.setNodeValue("dalao");//修改元素内容
//    node.firstChild().setNodeValue("diannao");
//    QDomNode newNode = node.firstChild();
//    node.replaceChild(newNode,oldNode);

    if(!file.open(QFile::WriteOnly|QFile::Truncate))//重写文件,如果不用truncate就是在后面追加内容,就无效了
    {
        QMessageBox::warning(this,"错误","更新XML内容,文件打开失败2");
        return;
    }
    QTextStream out_stream(&file);
    doc.save(out_stream,4);
    file.close();
}

XML效果演示

<?xml version='1.0' encoding='UTF-8'?>
<library>
    <book id="1" time="2020/6/3">
        <title>C++ primer</title>
        <author>Stanley B.Lippman</author>
    </book>
    <book id="2" time="2007/5/25">
        <title>Thinking in Java</title>
        <author>Bruce Eckel</author>
    </book>
    <book id="3" time="1813/1/27">
        <title>diannao</title>
        <author>Jane Austen</author>
    </book>
</library>

  • 10
    点赞
  • 114
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将XML文件的属性值显示在Qt的TableView上,您需要执行以下步骤: 1. 使用QtXML模块,加载并解析XML文件。您可以使用QXmlStreamReader或QDomDocument来处理XML文件。下面是使用QDomDocument的示例代码: ```cpp QFile file("your_xml_file.xml"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Failed to open XML file"; return; } QDomDocument doc; if (!doc.setContent(&file)) { file.close(); qDebug() << "Failed to parse XML"; return; } file.close(); ``` 2. 从解析后的XML文档中提取属性值,将其存储在Qt数据结构中,例如QList或QVector。 ```cpp QList<QStringList> data; // 存储属性值的数据结构 QDomElement root = doc.documentElement(); QDomNodeList nodeList = root.elementsByTagName("your_tag_name"); // 选择要显示的标签名 for (int i = 0; i < nodeList.count(); ++i) { QDomElement element = nodeList.at(i).toElement(); QStringList rowData; // 提取属性值并添加到rowData中 rowData << element.attribute("attribute_name"); // 将rowData添加到data中 data.append(rowData); } ``` 3. 创建一个自定义的QAbstractTableModel子类,以提供数据给TableView。 ```cpp class MyTableModel : public QAbstractTableModel { public: MyTableModel(const QList<QStringList>& data, QObject* parent = nullptr) : QAbstractTableModel(parent), m_data(data) { } int rowCount(const QModelIndex& parent = QModelIndex()) const override { if (parent.isValid()) return 0; return m_data.count(); } int columnCount(const QModelIndex& parent = QModelIndex()) const override { if (parent.isValid()) return 0; return m_data.isEmpty() ? 0 : m_data.first().count(); } QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { if (!index.isValid() || role != Qt::DisplayRole) return QVariant(); return m_data[index.row()][index.column()]; } private: QList<QStringList> m_data; }; ``` 4. 创建一个TableView实例,并使用自定义的TableModel来设置数据。 ```cpp QTableView* tableView = new QTableView(); MyTableModel* model = new MyTableModel(data); tableView->setModel(model); ``` 通过执行以上步骤,您就可以将XML文件的属性值显示在Qt的TableView上了。请根据您的实际需求修改代码,并确保在使用完数据后适当释放内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值