xmlqtqxmlstreamreader

How to add to an XML file structured like this in Qt?


How can I write this to an xml file using qt?

 <model>
  <column loop="true">`enter code here`
    <item2  color="#4d6862"  />
    <item2  color="#ff0000ff" />
    <item2  color="#ff00ff00" />
    <item2 color="#ff00ffff" />
    <item2 color="#ffff0000" />
    <item2 color="#ffff00ff" />
    <item2  color="#ffffff00" />
    <item2 color="#4d6862" />
  </column>
</model>

This looks promising ( Writing XML Nodes in QtXML (QDomElement) ) but it doesn't mention attributes.


Solution

  • You can do it with QXmlStreamWriter: http://qt-project.org/doc/qt-5/qxmlstreamwriter.html

    QXmlStreamWriter writer (&file);    // a QFile object, must be open for writing
    writer.setAutoFormatting(true);
    writer.writeStartDocument("1.0");
    writer.writeStartElement ("model");
    writer.writeStartElement ("column");
        writer.writeAttribute ("loop", "true");
    
        writer.writeStartElement ("item2");
        writer.writeAttribute ("color", "#4d6862");
        writer.writeEndElement ();
        // write all other items
    
    writer.writeEndDocument();   // this will close all open tags