xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="01">
<title>Qt</title>
<author>shiming</author>
</book>
<book id="02">
<title>linux</title>
<author>shiming</author>
</book>
</library>
在pro 加入 QT += xml
QDomDocument doc;
QFile file(":/my.xml");
if(!file.open(QIODevice::ReadOnly))
{
return 0;
}
if(!doc.setContent(&file))
{
file.close();
return 0;
}
file.close();
//获取doc的第一个节点,即xml说明
QDomNode firstNode = doc.firstChild();
//输出xml说明,nodeName()为xml, nodeValue()为版本和编码信息
qDebug() << firstNode.nodeName(); // xml
qDebug() << firstNode.nodeValue(); // "version='1.0' encoding='UTF-8'"
//返回根元素
QDomElement docElem = doc.documentElement(); // <library>
//返回节点的第一个子节点
QDomNode n = docElem.firstChild();
//如果节点不为空, 则转到下一个节点
while(!n.isNull())
{
if(n.isElement())
{
QDomElement e = n.toElement();
qDebug() << e.tagName(); //book
qDebug() << e.attribute("id"); //01 02
QDomNodeList list = e.childNodes();
//便利改列表
for(int i = 0; i < list.count(); i++)
{
QDomNode node = list.at(i);
if(node.isElement())
{
qDebug() << " " << node.toElement().tagName();
qDebug() << " " << node.toElement().text();
}
}
}
n = n.nextSibling();
}
输出结果:
"xml"
"version='1.0' encoding='UTF-8'"
"book"
"01"
"title"
"Qt"
"author"
"shiming"
"book"
"02"
"title"
"linux"
"author"
"shiming"