PDA

View Full Version : writing raw data into xml sub-node



elcuco
21st August 2014, 06:04
(continuing http://www.qtcentre.org/threads/60004-reading-XML-node-and-sub-nodes )

I am using QXmlStreamWriter, and under some conditions I need to write into a node, a text that contains raw xml, not encoded.



QString b = "<b>test 1 2 3 </b>";
QXmlStreamWriter stream(&output);
stream.writeStartDocument();
stream.writeStartElement("a");
stream.writeCharacters(b);
stream.writeEndElement();
stream.writeEndDocument();
stream.close();


In this example, "b" gets encoded into XML, which is usually desired, but not in this case.

One solution I have is to write the XML manually as a text file. This will work, but I feel this is ugly.

What other alternatives to I have?

anda_skoa
21st August 2014, 09:37
Have you tried writing into "output" after calling writeStartElement("a")?

Cheers,
_

elcuco
25th August 2014, 07:38
Is this what you recommend?


void test_save() {
QString b = "<b>test 1 2 3 </b>";
QByteArray bytes;
QBuffer output(&bytes);
output.open(QIODevice::ReadWrite);

QXmlStreamWriter stream(&output);
stream.writeStartDocument();
stream.writeStartElement("a");
output.write(b.toLatin1().constData(), b.length());
stream.writeEndElement();
stream.writeEndDocument();
output.close();
qDebug("%s", bytes.data());
}


This outputs:

<?xml version="1.0" encoding="UTF-8"?><a<b>test 1 2 3 </b>/>

See how "a" element is not closed? Note also how the "</a>" is missing, as well as document end. I wonder why it broke off so much.

wysota
25th August 2014, 12:45
How about using QXmlStreamWriter::writeCDATA()?

d_stranz
25th August 2014, 19:13
See how "a" element is not closed? Note also how the "</a>" is missing, as well as document end. I wonder why it broke off so much.

Because you told QXmlStreamWriter to write an empty "<a/>" element. By calling output.write() directly, you did something that the stream writer has no knowledge about. It doesn't know what you did "behind its back". As far as it knows, all you did was to tell it to start an "a" element, then immediately end it.

Try wysota's idea.

But why can't you simply write out the raw XML using QXmlStreamWriter? Are the "<b>" element names unknown at compile time? Or is it only the text inside the "b" element?