I want my application to be able to save some of it's objects to an XML file. I have written the code below, but i'm not sure if this is the best way to do it. Surely working with XML should be simpler.
By that i mean that the code i have is very repetitive as i have to create each node as well as the inner text node. Are there helper functions to simplify adding basic elements like this?
// Creates and returns an XML node that represents SomeObject
tempNode = doc.createElement("variable1");
tempNode.appendChild(doc.createTextNode(variable1));
root.appendChild(tempNode);
tempNode = doc.createElement("variable2");
tempNode.appendChild(doc.createTextNode(variable2));
root.appendChild(tempNode);
tempNode = doc.createElement("rectangle");
tempNode .setAttribute("x", getDimensions().x());
tempNode .setAttribute("y", getDimensions().y());
tempNode .setAttribute("width", getDimensions().width());
tempNode .setAttribute("height", getDimensions().height());
root.appendChild(tempNode);
// ... etc
return root;
}
// And elsewhere, write the xml node to a file
xmlDoc.appendChild(object->asXmlNode(xmlDoc));
stream << xmlDoc.toString(4);
// Creates and returns an XML node that represents SomeObject
QDomElement SomeObject::asXmlNode(QDomDocument& doc) {
QDomElement tempNode;
QDomElement root = doc.createElement("someobject");
tempNode = doc.createElement("variable1");
tempNode.appendChild(doc.createTextNode(variable1));
root.appendChild(tempNode);
tempNode = doc.createElement("variable2");
tempNode.appendChild(doc.createTextNode(variable2));
root.appendChild(tempNode);
tempNode = doc.createElement("rectangle");
tempNode .setAttribute("x", getDimensions().x());
tempNode .setAttribute("y", getDimensions().y());
tempNode .setAttribute("width", getDimensions().width());
tempNode .setAttribute("height", getDimensions().height());
root.appendChild(tempNode);
// ... etc
return root;
}
// And elsewhere, write the xml node to a file
QDomDocument xmlDoc;
xmlDoc.appendChild(object->asXmlNode(xmlDoc));
QTextStream stream(&file);
stream << xmlDoc.toString(4);
To copy to clipboard, switch view to plain text mode
Bookmarks