PDA

View Full Version : reading xml file



dreamer
4th May 2008, 21:32
I have an xml file like this:


<start_header>
"text1"
"text2"
</start_header>
<option>
"text3"
"text4"
</option>

...and so on


I'd like to extract just the Textelement between each pair of tag and write it
in a file.txt

File.txt content:
"text1"
"text2"
"text3"
"text4"

I use the special class QXmlStreamReader and i try to obtain this behaviour with this code:


QFile *file=new QFile("source.xml")
QFile *f=new QFile("output.txt");
if(!f->open(QIODevice::ReadWrite))
std::cout<<"f problem"<<std::endl;
if(!file->open(QIODevice::ReadWrite))
std::cout<<"f problem"<<std::endl;

QTextStream out(f);
QXmlStreamReader xml(file);

while(!xml.atEnd()){
if (xml.readNext() == QXmlStreamReader::StartElement)
out<<xml.readElementText()<<"\n";
}
f->close();
file->close();


The output file wasn't writed......
What's wrong with this code?
Is there an other method, to obtain the behaviuor I looked for?

aamer4yu
4th May 2008, 21:56
May be the xml data is not valid.
How can text1 , text 2 be in one tag ??
also try to debug and see what values u are getting for readNextElement.

dreamer
4th May 2008, 21:59
I create the xml file from a DOM tree, using the function save.

The element inside tags are QDomElement, while the text are QDomText......

stevey
5th May 2008, 02:01
The only thing I see wrong with that data is there's no root element. Try:


<root>
<start_header>
"text1"
"text2"
</start_header>
<option>
"text3"
"text4"
</option>
</root>


Keep in mind though that "text1" "text2" are one element's worth of data. It will actually be interpreted as:


"text1" "text2"

The XML standard treats each line of text as separated by one space, even you indent the lines one space will be used. I'm not sure what would happen to the " characters, maybe they're illegal as well. Everything is treated as text in the xml file itself so you don't need to qualify strings with double quotes.
If one of these elements need to be treated as an integer, you're schema can state the type or you just read the line, then cast / convert it to the type you need.