PDA

View Full Version : xml file append updated stream instead of updating it



alizadeh91
2nd October 2012, 17:06
Hi,
I wanna to open a xml file and update or add some elements and node into it. I've approximately done this but the problem is that it's not updating and add updated stream in end of xml file.
I think i must clear previous stream or file and then save it but i don't know how..
Here is my code:

In the meanwhile how can i clear a text file??!!!


QDomDocument doc("name");
QFile file(filePath);
if(!file.open( QFile::WriteOnly | QFile::ReadOnly | QFile::Text))
return false;
if(!doc.setContent(&file));
{
file.close();
return false;
}

//Parse XML Document
QDomElement docElem = doc.documentElement();

//finding an element
QDomElement dialsElement;
dialsElement = docElem.elementsByTagName("GaugeComponents").at(0).toElement().elementsByTagName("Dials").at(0).toElement();

//creating some elements
QDomElement dialElement = doc.createElement("Dial2");
QDomElement x_dialElement = doc.createElement("x");
x_dialElement.setNodeValue("hello");

dialElement.appendChild(x_dialElement);

dialsElement.appendChild(dialElement);

QTextStream out(&file);

doc.save(out,0);

file.close();

wysota
2nd October 2012, 20:49
Truncate the file before writing to it.

alizadeh91
3rd October 2012, 07:11
What the exactly Truncate does??

ChrisW67
3rd October 2012, 07:22
You have opened the file for read and write. You then read the file which leaves the file's current position pointing at the end. When you write that is where it writes from, i.e. it appends to the original file. Truncating the file (see QFile::resize()) resets the file size to zero and places the cursor position at zero also.

This whole exercise would have been easier if you opened the file for reading, read it, closed it. Then, having manipulated the DOM, opened the file for writing (which implicitly truncates the file), written it, then closed it.

alizadeh91
3rd October 2012, 07:28
Ok, got it :)