开发者

QString to XML in QT

I need to create XML file in QT, but i dont use 开发者_运维问答QT XML classes to create the XML data, but i create strings manually (which contains XML) and write it into the file, the reason for not using QT XML classes is, i need to preserve the order of attribute but if i use QT XMl classes it writes attribute in random order.

Everything was fine up to now, until i get the html text to be written as tag value in XML. i need to write HTML data as the QT XMl classes writes for e.g "This is <Test data>" should be written as "This is &lt:Test data&gt". here i have replaced the ";" with ":" for understanding purpose.

can anyone help me with any function in QString which can detect the XMl and convert it before writing into the file or while writing into file?


Check QXmlStreamReader and QXmlStreamWriter classes. They are in QtCore and really useful for XML handling.

You should do something like this:

QString string;
QXmlStreamWriter writer(&string);
// use QXmlStreamWriter class to generate the XML
writer.setAutoFormatting(true);
writer.writeStartDocument();
...
writer.writeStartElement("html");
writer.writeStartElement("a");
writer.writeAttribute("href", "http://example.com/");
writer.writeCharacters("My wonderful link");
writer.writeEndElement(); // a
writer.writeEndElement(); // html
...
writer.writeEndDocument();


Since your problem is that you can't use the QT XML classes due to its behaviour, I'm assuming you don't have a problem with using the QT XML module in your project. The only way, I can think of detecting is, validating the code and if it validates as valid XML (syntax only).

QString test = "<TestData>Valid XML</TestData>";
QString wrapper_start = "<?xml version=\"1.0\"?><dummyrootelement>";
QString wrapper_end = "</dummyrootelement>";
QDomDocument document;
if(document.setContent(wrapper_start + test + wrapper_end)) {
    // Valid XML, handle test here
} else {
    // Probably not valid XML
}

The reason you need wrapper_start and wrapper_end variables is since you may be handling XML fragments in between, you might be considering this as XML that needs to be processed:

<TestData>Data1</TestData><TestData>Data2</TestData>

but a parse error will be caused on this as an XML document needs to have a single root element.

Also, do note that, the above method is not a recommended by me, but I have mentioned it because I understand the pain and sympathize with anyone who has to maintain legacy systems. If your application relies on the ordering of attributes, I strongly suggest that you at least consider revising the architecture of your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜