tags:

views:

24

answers:

2

I have to create a backup XML file every few minutes, here's the current code:

            XElement xml = new XElement("Items",
            new XElement("Backup",
            new XElement("Console", consoleName),
            new XElement("Begin", beginTime),
            new XElement("End", endTime),
            new XElement("Time", totalTime),
            new XElement("Price", totalPrice)

            xml.Save("Items.xml");

The problem is that it re-creates the XML file everytime, thus only the last item being saved. What am I missing? Thanks.

A: 

I've tried this code (after changing the variables) and it worked correctly :

    XElement xml = new XElement("Items",
        new XElement("Backup",
        new XElement("Console", "aa"),
        new XElement("Begin", "bb"),
        new XElement("End", "cc"),
        new XElement("Time", "dd"),
        new XElement("Price", "ee")));

    xml.Save(@"C:\Items.xml");
M.H
Please re-read the question.
xmlfoo
A: 

To append node to existing .xml file.
First you create the Items.xml with empty child elements.

<?xml version="1.0" encoding="utf-8"?>
<Items>
</Items>

Next, use this code to load Items.xml and append node to it.

XElement xml = new XElement("Backup",
new XElement("Console", consoleName),
new XElement("Begin", beginTime),
new XElement("End", endTime),
new XElement("Time", totalTime),
new XElement("Price", totalPrice));

XDocument xdoc = XDocument.Load("Items.xml");
xdoc.Element("Items").Nodes().Last().AddAfterSelf(xml);  //append after the last backup element
xdoc.Save("Items.xml");
Lee Sy En
I don't want to create multiple xml files. I want to store the data into one single, isn't there a way to append it to an already existing XML file?
xmlfoo
I have edited my answer.
Lee Sy En