How to make xml parser more clear
-
I have an xml file built in this way:
@<?xml version="1.0" encoding="UTF-8"?>
<Draw>
<Input>
<Cells>
<width>100</width>
<height>28</height>
</Cells>
<Column>custom</Column>
<Custom>
<header id="0">one</header>
<header id="1">two</header>
<header id="2">three</header>
<header id="3">four</header>
<header id="4">five</header>
</Custom>
</Input>
<Output>
<Cells>
<width>82</width>
<height>20</height>
</Cells>
<Column>upper</Column>
<Custom>
<header id="0">alfa</header>
<header id="1">beta</header>
<header id="2">gamma</header>
<header id="3">delta</header>
<header id="4">epsilon</header>
</Custom>
</Output>
</Draw>
@And I'm trying to extrapolate the values of the header tag: since we have two sets of header tags (Input and Output) the only working code that I managed to work for now is this:
@
void MainWindow::readXmlFile() {
QString target;
QFile* file = new QFile("System/Settings.xml");
/* If we can't open it, let's show an error message. /
if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) return;
QXmlStreamReader xmlReader(file);
/ We'll parse the XML until we reach end of it./
while(!xmlReader.atEnd() && !xmlReader.hasError()) {
QXmlStreamReader::TokenType token = xmlReader.readNext();
if(token == QXmlStreamReader::StartDocument) {
continue;
}
/ If token is StartElement, we'll see if we can read it./
if (token == 4) {
if (xmlReader.name() == "Input" || xmlReader.name() == "Output") {
target = xmlReader.name();
if ((!(xmlReader.tokenType() == QXmlStreamReader::EndElement && xmlReader.name() == target))) {
if (xmlReader.tokenType() == QXmlStreamReader::StartElement) {
if (xmlReader.name() == "header") {
//headers->append(xmlReader.readElementText());
qDebug() << xmlReader.readElementText();
}
}
}
}
}
}
/ Error handling. */
if(xmlReader.hasError()) {
QMessageBox::critical(this,
"QXSRExample::parseXML",
xmlReader.errorString(),
QMessageBox::Ok);
}
xmlReader.clear();
}
@Since this code seems very repetitive, especially from line 15 to 18, could you help me to make it a little cleaner?
Thanks in advance
-
Hi,
You should have a look at the QXmlStream Bookmarks Example