Farmer
Farmer

Reputation: 10993

Why the XML Element is not appended at the end of the file

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 ?

Upvotes: 1

Views: 180

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

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" using IsolatedStorageFile's DeleteFile API, and then copy "lampe_tmp.xml" to "lampe.xml" using the MoveFile API.

using (IsolatedStorageFileStream isoStore = new IsolatedStorageFileStream("lampes_tmp.xml", FileMode.Open, store)) {
    // the code from your post that modifies XML goes here...
}
IsolatedStorageFile.DeleteFile("lampes.xml");
IsolatedStorageFile.MoveFile("lampes_tmp.xml", "lampes.xml");

Upvotes: 1

Guffa
Guffa

Reputation: 700592

You are writing to the same stream that you read from. The file position will be at the end of the file when you start to write, so it will append to the file.

Either reset the position of the stream before writing, or close the stream and open a new stream for writing.

Upvotes: 0

Related Questions