基于 QDom
废话不多说
QString mdk_xml::xmlToQString(const QString &filename)
{
ret_str.clear();
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(nullptr, "Err", "Cannot open file for reading!");
return ret_str;
}
QDomDocument doc;
QString strErr;
int iErrCount;
int iErrLine;
if(!doc.setContent(&file,false,&strErr,&iErrLine,&iErrCount))
{
qDebug() << "xml err:" << strErr << "line" << iErrLine << "count" << iErrCount;
file.close();
return "err";
}
file.close();
QDomElement root = doc.documentElement();
qDebug() << root.nodeName();
xml_node(root);
return ret_str;
}
void mdk_xml::xml_node(QDomNode &node)
{
static uint8_t a=0;
static QString space="";
static uint16_t chird_index=0;
QString str;
QDomNode child;
QDomNode next;
if(a>20)//20/2=10 最多10级child
{
qDebug() << "err"<<a;
return;
}
space += " ";
a+=2;
child = node.firstChild();
if(child.isElement())
{
str = space + node.nodeName();
ret_str.append(str);
ret_str.append("\r\n");
xml_node(child);
}
else
{
str = space + node.nodeName() +": "+node.toElement().text();
ret_str.append(str);
ret_str.append("\r\n");
}
next = child.nextSibling();
while(1)
{
if(next.isElement())
{
xml_node(next);
}
else
{
space = space.left(a);
if(a>=2) a-=2;
break;
}
next = next.nextSibling();
}
}