一.对QDomDocument和QDomnode的理解node
QDom前缀的都是表明节点类型。因此有,QDomElement表明一个Element节点,而QDomText表明一个Text节点。QDomNode类能够存储任意类型的节点。若是想进一步处理一个节点,首先必须把它转化为正确的数据类型。QDomNode调用toElement()以把它转化成QDomElement,而后调用tagName()来得到元素的标签名称。若是节点不是Element类型,那么toElement()函数就返回一个空QDomElement对象和一个空标签。app
二.几种操做:dom
QFile file(filename); if(file.open(QFile::ReadOnly | QFile::Text)){ std::cerr<<"Error:cannot read file"<<qPrintable(filename)<<":"<<qPrintable(file.errorString())<<std::endl; return false; } QString errorStr; int line; int errorColumn; QDomDocument doc;//定义一个dom文件 if(!doc.setContent(&file,false,&line,&errorColumn)) { std::cerr<<"error"<<endl; } QDomElement root = doc.docmentElement(); if(root.tagName() != "book") { ..... }
(1) 对节点的操做函数
节点操做: QDomNode child = QDomElement element.firstChild(); while(!child.isNull()) { if(child.toElement().tagName() == "myName") { } child = child.nextSibling(); }
(2) XML文件与ini同样,xml一般用来进行软件配置spa
Qt中实现对xml读写操做的类是QDomDocument相关的类,通常状况下须要包含下列三个头文件:code
#include <QFile> #include <QtXml\QtXml> #include <QtXml\QDomDocument>
(3)写XMLxml
主要会用到下面的几个函数:对象
QDomDocument doc; QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); doc.appendChild(instruction); QDomElement root = doc.createElement("HInfoData");//建立根节点 doc.appendChild(root);//添加根节点 QDomElement strMac = doc.createElement("Mac");//建立元素节点 root.appendChild(strMac);//添加元素节点到根节点 QDomText strMacNodeText = doc.createTextNode(data._strMac);//建立元素文本 strMac.appendChild(strMacNodeText);//添加元素文本到元素节点
(4)保存xim文件blog
QFile file("./test.xml"); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) return false; QTextStream out(&file); out.setCodec("UTF-8"); doc.save(out, 4, QDomNode::EncodingFromTextStream); file.close();
(5)读xml文件element
QDomDocument doc; QFile file("./test.xml"); if (!file.open(QIODevice::ReadOnly)) { return false; } if (!doc.setContent(&file)) { file.close(); return false; } file.close();