xmlfoo
xmlfoo

Reputation: 13

XElement Save question

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.

Upvotes: 1

Views: 4883

Answers (2)

bla
bla

Reputation: 5480

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");

Upvotes: 4

Mohamad Alhamoud
Mohamad Alhamoud

Reputation: 4929

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");

Upvotes: 1

Related Questions