我对xml不太满意,但是我的基本xml文件看起来像这样。
<MAIN_HEADER>
<HEADER>
<TITLE>my_title</TITLE>
<AUTOR>DNL</AUTOR>
<NAME>John</NAME>
<AGE>abc</AGE>
<SEX>male</SEX>
<PLACE>abc</PLACE>
<INI_FILE>abc</INI_FILE>
</HEADER>
我想做的是,我需要找到2-3个标签,例如NAME&SEX,并将属性(John,Male)存储在另一个变量中。
到现在为止,我已经能够使其读取xml文件。
void MainWindow::XMLParser()
{
QString path=MainWindow::getWorkingDirectory()+"\\0_Config\\";
QString string;
string = path + ui->ConfigFiles_combo->currentText(); \\THIS IS WHERE´IT DETERMINES WHICH XML FILE IT IS
qDebug()<<string;
QDomDocument document;
//load the file
QFile file(string);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Failed to open the file";
}
else
{
if(!document.setContent(false))
{
qDebug()<<"Failed to load document";
}
file.close();
}
QDomElement root = document.firstChildElement();
qDebug()<<"finished";
}
如何使它搜索确切的标签并将其存储在另一个变量中?
你为什么setContent(false)
又有?看起来您刚刚复制了The Badger的代码。尝试这个。
void MainWindow::XMLParser()
{
// don't worry about path separator, Qt will take of it
QString string = MainWindow::getWorkingDirectory() + "/0_Config/" + ui->ConfigFiles_combo->currentText();
qDebug()<<string;
QDomDocument document;
//load the file
QFile xmlFile(string);
if (!xmlFile.exists() || !xmlFile.open(QFile::ReadOnly | QFile::Text)) {
qDebug() << "Check your file";
return;
}
QDomDocument domDocument;
domDocument.setContent(&xmlFile);
QDomElement topElement = domDocument.documentElement();
QDomNode domNode = topElement.firstChild();
while (!domNode.isNull()) {
QDomElement domElement = domNode.toElement();
if (!domElement.isNull()) {
//qDebug() << domElement.tagName();
if (domElement.tagName() == "HEADER") {
QDomNode node = domElement.firstChild();
while (!node.isNull()) {
QDomElement element = node.toElement();
if (!element.isNull()) {
const QString tagName(element.tagName());
if (tagName == "NAME") {
qDebug() << "Name is:" << element.text();
} else if (tagName == "SEX") {
qDebug() << "Sex is:" << element.text();
}
}
node = node.nextSibling();
}
}
}
domNode = domNode.nextSibling();
}
}
这是我的控制台输出
Name is: "John"
Sex is: "male"
Name is: "Doe"
Sex is: "male"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句