I’m trying to add an Element to an XML file in the IsolatedStorage, but instead of adding it at the of the root, the file is duplicated and added at the end :
<?xml version="1.0" encoding="utf-8"?>
<root>
<lampe id="1" nom="lampe1" content="Tables" header="Lampes de la cuisine" adresse="A1" />
<lampe id="2" nom="lampe2" content="Porte et garage" header="Lampe du jardin" adresse="C3" />
</root><?xml version="1.0" encoding="utf-8"?>
<root>
<lampe id="1" nom="lampe1" content="Tables" header="Lampes de la cuisine" adresse="A1" />
<lampe id="2" nom="lampe2" content="Porte et garage" header="Lampe du jardin" adresse="C3" />
<child attr="1">data1</child>
</root>
This is the code I’m using :
_xdoc = new XDocument();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isoStore = new IsolatedStorageFileStream("lampes.xml", FileMode.Open, store))
{
_xdoc = XDocument.Load(isoStore);
int nextNumber = _xdoc.Element("root").Elements("lampe").Count() + 1;
XElement newChild = new XElement("lampe", "data" + nextNumber);
newChild.Add(new XAttribute("attr", nextNumber));
_xdoc.Element("root").Add(newChild);
_xdoc.Save(isoStore);
}
}
What I’m missing here ?
Reading and writing the same file is not a good idea. Your XML is constructed correctly, it’s just written incorrectly.
One approach that should work is to write the file to a different location (say
"lampe_tmp.xml"), close and remove the original"lampe.xml"usingIsolatedStorageFile‘sDeleteFileAPI, and then copy"lampe_tmp.xml"to"lampe.xml"using theMoveFileAPI.