gpt4 book ai didi

c++ - QT:读取 xml 文件并使用 DOM 解析器解析它

转载 作者:行者123 更新时间:2023-11-30 03:46:52 26 4
gpt4 key购买 nike

我不太擅长 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"

关于c++ - QT:读取 xml 文件并使用 DOM 解析器解析它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33935582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com