遍历xml(打印节点名和属性)
【核心方法】
void traverseNode(QDomElement e) {
QDomNamedNodeMap attrs = e.attributes();
qDebug() << e.nodeName() << e.text();
// 遍历属性
for (int i = 0; i < attrs.count(); i++)
{
QDomNode attr = attrs.item(i);
if (!attr.isNull() && attr.isAttr()) {
qDebug() << "-" << attr.nodeName() << attr.nodeValue();
}
}
// 遍历子节点
QDomNode child = e.firstChild();
while (!child.isNull() && child.isElement())
{
QDomElement childele = child.toElement(); // try to convert the node to an element.
traverseNode(childele);
child = child.nextSibling();
}
}
【调用】
QFile file("/Users/zdy/Desktop/My.xml");
QDomDocument document;
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Failed to open file";
return;
}
else
{
if (!document.setContent(&file))
{
qDebug() << "Failed to open document";
return;
}
file.close();
}
QDomElement root = document.documentElement();
traverseNode(root);
网友评论