PDA

View Full Version : QXmlStreamWriter and while/if loop



prophet0
16th April 2012, 23:02
i cant seem to get my XML to write properly in a while/if loop

please see my code as follows



QXmlStreamWriter output2(&iconfile);
output2.setAutoFormatting(true);
output2.writeStartDocument();
output2.writeStartElement("Menu");
while (sqlSelFrmView.next())
{
QString levelString = sqlSelFrmView.value(2).toString();
output2.writeStartElement("Parent");
if(levelString == "1")
{

output2.writeTextElement("Root", sqlSelFrmView.value(1).toString());
}

if(levelString != "1")
{
output2.writeStartElement("Child");
output2.writeTextElement("Name", sqlSelFrmView.value(1).toString());
}
output2.writeEndElement();
}
output2.writeEndElement();
output2.writeEndElement();
output2.writeEndDocument();


but the result of my xml document is not as expected



<Menu>
<Parent>
<Root>Telus</Root>
</Parent>
<Parent>
<Child>
<Name>Smartphones</Name>
</Child>
<Parent>
<Child>
<Name>Rate Plans</Name>
</Child>
<Parent>
<Child>
<Name>Coverage</Name>
</Child>
<Parent>
<Child>
<Name>Support</Name>
</Child>
<Parent>
<Child>
<Name>Promotions</Name>
</Child>
<Parent>
<Root>Dine.To</Root>
</Parent>
<Parent>
<Root>TourismTo</Root>
</Parent>
</Parent>
</Parent>
</Parent>
</Menu>


my desired result is



<Menu>
<Parent>
<Root>Telus</Root>
<Child>
<Name>Smartphones</Name>
</Child>
<Child>
<Name>Rate Plans</Name>
</Child>
</Parent>
<Parent>
<Root>Telus</Root>
<Child>
<Name>Smartphones</Name>
</Child>
<Child>
<Name>Rate Plans</Name>
</Child>
</Parent>
<Parent>
<Root>Dine.To</Root>
</Parent>
<Menu>


any pointers would be much appreciated

wysota
16th April 2012, 23:18
Your code structure is "flat" so you get flat output. You need to make your code hierarchical -- if you expect to read a child, don't close the parent tag until you know there is no child. If you can't handle that directly then first use your flat code to create a regular tree of objects in memory and then traverse this tree to write it to xml, it should be much simpler then because you'll be able add children to already created elements.