PDA

View Full Version : [SAX] program loop while reading XML file



kabanek
19th September 2010, 10:29
hi,

I'm trying to parse XML file with SAX, but my program started looping. Here is my function:

void JTemplate::readStyles(QXmlStreamReader &xml, QString parentId, QString id, JList<JCss> &css)
{
if (xml.name() == parentId)
{
qDebug()<<"Parsuje: "<<parentId;

while (!(xml.name() == parentId && xml.tokenType() == QXmlStreamReader::EndElement))
{
xml.readNext();

JCss _result;
_result.setName(xml.attributes().value("name").toString());
qDebug()<<"Nazwa stylu Css to: "<<_result.getName();
xml.readNext();

while (!(xml.name() == id && xml.tokenType() == QXmlStreamReader::EndElement))
{
qDebug()<<"Styl: " << xml.name().toString();
_result.setStyle(toCssStyle(xml.name().toString()) , xml.readElementText());
}

css.add(_result);

xml.readNext();
continue;
}
}
}

This function was written to parese parts of XML file like:

<visited>
<link name="bink1_visited">
<FontColor>red</FontColor>
<FontColor2>green</FontColor2>
</link>
</visited>
When I use this function for example

readStyles(_xml, "visited", "link", CssAnchorVisited);
the loop

while (!(xml.name() == id && xml.tokenType() == QXmlStreamReader::EndElement))
is working indefinitely. Why? What do I do wrong?

And the second thing, I cannot read arguments (in my code "name") in line:

_result.setName(xml.attributes().value("name").toString());

ps. Sory for my English :-) I'm still learning

e8johan
20th September 2010, 08:13
As for the while statement, you have two readNext in the loop - perhaps you skip the end tag that you are looking for.

wysota
20th September 2010, 08:24
the loop

while (!(xml.name() == id && xml.tokenType() == QXmlStreamReader::EndElement))
is working indefinitely. Why? What do I do wrong?
What is this while() loop supposed to do?


And the second thing, I cannot read arguments (in my code "name") in line:

_result.setName(xml.attributes().value("name").toString());
Attributes are reported in StartElement and not EndElement.

I'm not sure what you want to achieve but I think you are overcomplicating things, try this:

JList<JCss> JTemplate::readStyles(QXmlStreamReader &xml, QString parentId, QString id )
{
JList<JCss> css;
Q_ASSERT(xml.name() == parentId);
while(xml.readNextStartElement() {
if(xml.name() == parentId) {
while(xml.readNextStartElement()){
if(xml.name() == id){
JCss _result;
_result.setName(xml.attributes().value("name").toString());
qDebug() << "Styl:" << xml.name();
_result.setStyle(...); // I don't think readElementText() will work here without using a CDATA section
css.add(_result);
} else xml.skipCurrentElement(); // skip unknown tags
}
xml.skipCurrentElement(); // read until end of parentId tag
} else xml.skipCurrentElement(); // skip unknown tags
}
return css;
}