1. xml文件
test.xml
文件内容
<?xml version="1.0" encoding="utf-8"?>
<library>
<book1>
<id>00000001</id>
<name>1111</name>
</book1>
</library>
2. 代码
void DataXml::read()
{
//打开文件
QFile file("test.xml");
if(!file.open(QFileDevice::ReadOnly)){
QMessageBox::information(NULL, tr("提示"), tr("结果文件打开失败,errNo:1"));
return;
}
//创建XML对象
QDomDocument doc;
if (!doc.setContent(&file)) {
QMessageBox::information(NULL, tr("提示"), tr("结果文件打开失败, errNo:2"));
file.close();
return;
}
//读取节点
QDomElement root = doc.documentElement();
QDomNodeList bookList = root.elementsByTagName("book1");
QDomElement book = bookList.at(0).toElement();
QString id = queryNodeValue(book, "id");
QString name = queryNodeValue(book, "name");
//关闭文件
file.close();
}
//注意:firstChild()是重点
QString DataXml::queryNodeValue(QDomNode node, QString nodeName)
{
return node.namedItem(nodeName).firstChild().nodeValue();
}