saving to xml document

2019-06-24 04:55发布

问题:

I am "trying" to figure out how to create a Windows Phone 7 application and I would like to update/save an xml file with the following function:

        XDocument xmlDoc = XDocument.Load("myApp.xml");

        xmlDoc.Element("ocd").Add(new XElement("vDetails", new XElement("itemName", this.tb_Name.Text),
            new XElement("Date", System.DateTime.Now.ToString()), new XElement("itemValue", "")));

        xmlDoc.Save("data.xml");

However the xmlDoc.Save line is giving an error: The best overloaded method match for "System.Xml.Linq.XDocument.Save(System.Xml.XmlWriter) has some invalid arguments.

What do I need to do to correct this?

回答1:

You need to save to isolated storage (or a few other places). Get the isolated storage for your application, open a stream to a file, and save to the stream:

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (Stream stream = storage.CreateFile("data.xml"))
    {
        doc.Save(stream);
    }
}


回答2:

The Windows Phone developer blog goes talks application execution model in great depth.

I think it is important to distinguish between application 'closing' and an application being tombstoned.

Application Closing is simply the outcome of the user pressing the hardware Back button enough times to navigate backwards through the pages of your application, past the application’s first page.

Application Deactivated occurs when a different application takes control of the foreground - for example, an incoming phone call, launching a chooser, or the user pressing the Windows button. In both cases, your application will be deactivated (not closed). Before we step into the subtleties of the Deactivated event, let’s make sure we all understand that upon Deactivation, your application gets terminated (at the end). It's that simple; your code can’t run in the background, therefore your application gets terminated. However, unlike an application that is closed, a deactivated application gets tombstoned. Don’t get confused, a tombstoned application’s process still gets terminated. But unlike a closed application, where the WP operating system removes any trace of the application, when an application is deactivated, the WP operating system stores a record (a tombstone) of the application's state. Basically, the WP operating system keeps a tombstone of the application that becomes part of the phone’s application back-stack, which is a journal that enables the use of the hardware Back button to enhance navigation functionality.

Application Execution Model

As for testing, an idea may be to refactor the code and add logging for various event points like closing or being tombstoned etc.