您的位置:首页 > 编程语言 > Qt开发

qt中关于xml的一些知识点

2017-08-29 10:25 387 查看
其实对于qt中的xml分为QDomDocument和QXmlStreamReader两个类。

QDomDocument:处理较小的XML文件;

QXmlStreamReader:处理比较大的XML文件;

本文主要讲的是:QDomDocument;

在把数据写入到XML文件中,主要操作包括了:

1.创建根节点:QDomElement root=doc.documentElement(“rootName”);

2.创建元素节点:QDomElement element=doc.createElement(“nodeName”);

3.添加元素节点到根节点:root.appendChild(element);

4.创建元素文本:QDomText nodeText=doc.createTextNode(“text”);

5.添加元素文本到元素节点:element.appendChild(nodeText);

说个例子吧:

QDomDocument doc;
QDomProcessingInstruction instruction=doc.createProcessingInstruction("xml","version=\"1.0\"encoding=\"UTF-8\"");
doc.appendChild(instruction);
QDomElement root=doc.createElement("Notes");
doc.appendChild(root);
QDomElement note=doc.createElement("note");
root.appendChild(note);
QDomElement no=doc.createElement("no");
note.appendChild(no);
QDomText no_text=doc.createTextNode("001");
no.appendChild(no_text);
QFile file("test.xml");
if(!file.open(QIODevice::WriteOnly)|QIODevice::Truncate|QIODevice::Text))
return;
QTextStream out(&file);
out.setCodec("UTF-8");
doc.save(out,4,QDomNode::EncodingFromTextStream);
file.close();

下面是编译完之后形成的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<Notes>
<note>
<no>001</no>
</note>
</Notes>


在读取XML文件,所进行的主要操作:

1.读取根节点:QDomElement root=doc.documentElement();

2.读取第一个子节点:QDomNode node=root.firstChild();

3.读取下一个子节点:node=node.nextSibling();

4.匹配节点标记:node.toElement().tagName()==”note”

5.读取节点文本:no=childNode.toText().data();

说个例子:

void MainWindow::parseAttr(const QDomElement &element)
{
QDomNode node=element.firstChild();
while(!node.isNull())
{
if(node.toElement().tagName()=="note")
{
parseAttr(node.toElement());
}
else if(node.toElement().tagName()=="no")
{
QDomNode childNode=node.firstChild();
if(childNode.nodeType()==QDomNode::TextNode)
{
no=childNode.toText().data();
}
}
else if(node.toElement().tagName()=="name")

node=node.nextSibling();
}
}


删除XML节点文件的时候,主要用到的函数为:root.removeChild(node);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  qt xml