QT 之XML 使用DOM的基本操作

简介

  1. XML 介绍
  2. 使用DOM读取XML文件
  3. 创建XML文件
  4. 增加节点、删除,查找、更新

1 XML 介绍

XML是一种类似于HTML的标记语言,但它的设计目的是用来传输数据,而不是显示数据。XML的标签没有被预定义,用户需要在使用时自行进行定义。XML使用的树形结构更能表现出数据的包含关系,作为一种文本文件格式,XML简单明了的特性使得它在信息存储和描述领域非常流行。

例如:

<?xml version="1.0" encoding="UTF-8"?>
<main>
	<first name = "aaaa">
		<id>12</id>
	</first>
	<second name = "bbb">
	<type> int  </type>
	</ second>
</main>

每个XML文件都是由XML说明开头,XML中可以包含多个元素,也可以嵌套多个节点,但是根节点只能包含一个。

2 使用DOM读取XML文件

使用DOM读取XML文件需要在(.pro)文件中加入QT += xml一行代码。

Dom(Document Object Model,即文档对象模型)把XML文档转换成应用程序可以遍历的树形结构,这样便可以随机访问其中的节点。它的缺点是需要将整个XML文档读入内存,消耗内存较多。
QT中使用QDomProcessingInstruction类来表明XML说明,元素对应QDomElement类,属性对应QDomAttr类,文本内容由QDomText类表示,所有的DOM节点,比如这里的说明、元素、属性和文本等,都是用QDomNode来表示,然后使用对应的 isProcessingInstruction()、isElement()、isAttr()和isText()等函数来判断是否是该类型的元素,如果是,可以使用toProcessingInstruction()、toElement()、toAttr()和toText()等函数转换为具体的节点类型。

实例:项目MyDom
(1)、首先在项目文件.pro中加上 QT += core xml
(2)、main.cpp中代码如下:

#include <QCoreApplication>
#include <QDomDocument>
#include <QFile>
#include <QDebug>

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

    QDomDocument doc;

    QFile file("my.xml");

    if(!file.open(QIODevice::ReadOnly))
    {

        return 0;
    }
    if(doc.setContent(&file))//转化为dom文件
    {
        qDebug() << "file.open";
        file.close();
        return 0;
    }
    file.close();

    QDomNode firstNode = doc.firstChild();

    qDebug() << firstNode.nodeName() << firstNode.nodeValue();

    return a.exec();
}

(3)、这里我们看到main.cpp文件中需要打开文件my.xml;此处需要在于MyDom.exe同级中创建一个如下所示的my.xml;

<?xml version="1.0" encoding="utf-8"?>

<content>
	<node id = "01">
		<title>Dom</title>
		<author>cqc</author>
	</node>
	<node id = "02">
		<title>Linux</title>
		<author>cqc1<author>
	</node>
</content>

(4)、程序运行如下
在这里插入图片描述

如果这边不想看到最外层的双引号,可以将源码中得qDebug()语句更改如下:

qDebug() << qPrintable(firstNode.nodeName())
<< qPrintable(firstNode.nodeValue());

文档解析的步骤:举例如下代码

QFile file("test.xml");
QDomDocument doc;

if(!file.open(QIODevice::ReadOnly))
{
	qDebug() << "open the file failed!";
	return;
}

if(!doc.setContent(&file))
{
	qDebug() << "doc error";
	return;
}
QDomElement root = doc.documentElement();
QDomElement node = root.firstChildElement();//获取根节点

while(!node.isNull())
{
	if(node.tagName() == "fileName" && node.hasAttribute("type"))
	{
		QString type = node.attributeNode("type").value();
		qDebug() << type;
	}
	QDomElement elementNode = node.firstChildElemnet();
	while(!objNode.isNull())
	{
		elementNode = elementNode.nextSiblingElement(); 
		qDebug() << elementNode.tagName();
	}
	node = node.nextSiblingElement();//将统计的下一个节点赋值给当前的node
}
file.close();

与之相对应的 XML 举例

<fileName type = "registration form">
	<param value = "man" type= "sex">
	<param value = "woman" type= "sex">
</fileName>
<fileName type = "info">
	<param value = "18" type= "age">
	<param value = "19" type= "age">
</fileName>

上述文章中主要记叙了如何进行遍历读取XML中的节点

添加和修改和删除中的XML节点

举例如下:

#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QDomComment>


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

    QString strFile = QString("../test.xml");

    if(QFile::exists(strFile))//如果文件已经存在,进行删除
    {
        QFile::remove(strFile);
    }

    QFile file(strFile);
    if(!file.open(QIODevice::ReadWrite))
    {
        return -1;//新建文件打开失败
    }

    QTextStream stream(&file);
    stream.setCodec("UTF-8");//使用utf-8格式

    //xml文件中只能有一个根节点,如果有多个根节点则只读取第一个跟节点的内容
    QDomDocument doc;
    QDomProcessingInstruction xmlInstruction  = doc.createProcessingInstruction("xml"," version = \"1.0\" encoding =\"UTF-8\" standalone=\"yes\" ");
    QDomComment comment = doc.createComment(QString::fromUtf8("备注"));
    QDomProcessingInstruction styleInstruction = doc.createProcessingInstruction("说明",QString::fromUtf8("说明的内容"));
    doc.appendChild(xmlInstruction);  // 开始文档(XML 声明)
    doc.appendChild(comment);  // 注释
    doc.appendChild(styleInstruction);

    //添加根节点
    QDomElement root = doc.createElement("root");
    root.setAttribute("id", "888");
    doc.appendChild(root);

    QDomElement name = doc.createElement("Name");
    name.setAttribute("name", QString::fromUtf8("王均"));//向Name节点中添加属性值
    root.appendChild(name);//将Name节点添加到root节点上

    QDomElement age = doc.createElement("Age");
    age.setAttribute(QString::fromUtf8("年龄"),"32");
    root.appendChild(age);

    QDomElement math = doc.createElement("math");
    QDomText text = doc.createTextNode(QString::fromUtf8("九十"));
    math.appendChild(text);//像math节点添加内容
    root.appendChild(math);

    QDomElement chinese = doc.createElement(QString::fromUtf8("语文"));
    text = doc.createTextNode("88");
    chinese.appendChild(text);
    root.appendChild(chinese);

    QDomElement contentNode = doc.createElement("content");
    contentNode.setAttribute("count", "2");
    QDomElement numberNode = doc.createElement("numb");
    numberNode.setAttribute("size", "5m");
    QDomElement numberNode1 = doc.createElement("numb");
    numberNode1.setAttribute("size", "10m");
    contentNode.appendChild(numberNode);
    contentNode.appendChild(numberNode1);
    root.appendChild(contentNode);

    //删除节点并修改节点中属性值
    contentNode.removeChild(numberNode1);
    contentNode.setAttribute("count", "1");
    root.removeChild(age);

    //保存到xml文件
    doc.save(stream, 4, QDomNode::EncodingFromTextStream);
    file.close();
    return a.exec();
}

生成文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--备注-->
<?说明 说明的内容?>
<root id="888">
    <Name name="王均"/>
    <math>九十</math>
    <语文>88</语文>
    <content count="1">
        <numb size="5m"/>
    </content>
</root>

综上所述为XML的常见操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值