PDA

View Full Version : Problems writting a svg file



Hogwarts
6th July 2011, 21:43
I need to change some element attributes of a xml file. I've been trying to achieve this using QXmlStreamWriter class, but it does not work fine, because when I call the function, all elements are deleted of the xml file, except the changed attribute.
For example, I want to change the width of a rectangle, in a SVG file, keeping the other elements and attributes intact.
Here is my code:


void Editor::changeElementAttribute(int pos, QVariant newData)
{
DomItem *item = static_cast<DomItem*>(treeView->currentIndex().internalPointer());
QDomNode node = item->node();
QDomNamedNodeMap attributeMap = node.attributes();

file.setFileName(currentPath);

if (!file.open(QFile::WriteOnly | QFile::Text))
{
QMessageBox::warning(new QWidget(), tr("SVG Editor"),
tr("Cannot write file %1:\n%2.").arg(currentPath)
.arg(file.errorString()));
return;
}

stream.setDevice(&file);
stream.writeStartElement(node.nodeName()); //tagname
stream.writeAttribute(attributeMap.item(pos).nodeN ame(), newData.toString()); //attribute and value
stream.writeEndElement();
}

Any help is welcome.
Thanks in advanced!

d_stranz
6th July 2011, 22:16
Your code is doing exactly what you told it to do: Open the file, erase everything in it, write out a single element tag, write a single attribute for that element, then close the element and the file. Why did you think that by doing that, it would somehow magically remember everything that was in it already? XML files are no different than any other text file, there is just a fancy API to add structure to the text.

If you are already keeping the DOM document tree in memory (it looks like you are, since you associate DOM items with tree items), then you need to simply change the attribute in the attribute map. After the user is finished editing, then you need to rewrite the entire DOM tree back out to the file, using QDomDocument::save();

Hogwarts
7th July 2011, 15:38
Thanks a lot. I've been working a while with QDomDocument and I had not seen the save() function. I know all everything is in the assistant, but...
Thanks a lot...I can now either save the changes.
The code was so:

void Editor::changeElementAttribute()
{
QFile file(currentPath);
if (!file.open(QFile::WriteOnly | QFile::Text))
{
QMessageBox::warning(new QWidget(), tr("SVG Editor"),
tr("Cannot write file %1:\n%2.").arg(currentPath)
.arg(file.errorString()));
return;
}
QTextStream out(&file);
document.save(out, 2);
}