简体   繁体   English

如何在UWP应用程序中加载,编辑和保存XML

[英]How to load, edit and save xml in uwp app

Title says it all really. 标题确实说明了一切。 I've been stuck on this one for days and would appreciate some help. 我已经坚持了好几天,不胜感激。 I've a main page and a settings page when the main page loads first time it tests for settings.xml in local folder and copies it if not found. 当主页第一次加载时,我有一个主页和一个设置页面,它会在本地文件夹中测试settings.xml并在找不到时进行复制。 Then when the user opens settings page it's supposed to load details from local folder allowing the user to edit before saving them back to the local folder from OnNavigatedFrom event. 然后,当用户打开设置页面时,应该从本地文件夹加载详细信息,从而允许用户进行编辑,然后再将其从OnNavigatedFrom事件保存回本地文件夹。

Code to load from installation folder to local folder 从安装文件夹加载到本地文件夹的代码

// Has the file been copied already?
        bool blFileExist = false;
        try
        {
            await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
            // No exception means it exists
            blFileExist = true;
            btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
        }
        catch (System.IO.FileNotFoundException)
        {
            // The file obviously doesn't exist
            blFileExist = false;
            btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);

        }
        catch (Exception)
        {

        }

        if (!blFileExist)
        {
            try
            {
                // Cant await inside catch, but this works anyway
                StorageFile stopfile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("settings.xml");
                await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);
            }
            catch (System.IO.FileNotFoundException)
            {

            }
            catch (Exception)
            {

            }
        }

Code to load and save settings page 加载和保存设置页面的代码

private void loadSettings()
    {
        try
        {
            doc = XElement.Load("settings.xml");

            nAIPlayers = int.Parse(doc.Element("ai_players").Value);
            strCardBack = doc.Element("back").Value;

            comboBoxAIPlayers.SelectedIndex = nAIPlayers - 1;
        }
        catch (System.IO.FileNotFoundException)
        {

        }
        catch (Exception ex)
        {

        }

    }

    private async void saveSettings()
    {
        //try
        //{
            StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                doc.SetElementValue("ai_players", nAIPlayers);
                doc.SetElementValue("back", "Back_0");
                doc.Save(fileStream);
            }
        /*}
        catch (System.IO.FileNotFoundException)
        {

        }
        catch (Exception ex)
        {

        }*/
    }

I think the problem is I'm accessing the local file to save it and the installation file to load it. 我认为问题是我正在访问本地文件以保存它,并在安装文件中加载它。 The result is no matter what I save it always reads the values in the original settings.xml 结果与我保存的内容无关,它始终读取原始settings.xml中的值

How do I load this from the local folder? 如何从本地文件夹加载此文件?

doc = XElement.Load("settings.xml"); doc = XElement.Load(“ settings.xml”);

Update 更新资料

On the first iteration the code runs fine and the settings page code opens as it should. 在第一次迭代中,代码可以正常运行,并且设置页代码将按应有的方式打开。 It's only after leaving the settings page and running saveSettings() method that it fails and throws an error when reloading the settings page and running loadSettings(). 只有在退出设置页面并运行saveSettings()方法后,它才会失败,并在重新加载设置页面并运行loadSettings()时引发错误。

System.Xml.XmlException: Data at the root level is invalid. System.Xml.XmlException:根级别的数据无效。 Line 5, position 12 5号线,位置12

You are doing it wrong because you are using XElement.Load(string) where string stands for URI , which in this case should be: 您做错了,因为您使用的是XElement.Load(string) ,其中string表示URI ,在这种情况下应该是:

The Uri parameter must be a file system relative or absolute path. Uri参数必须是文件系统相对或绝对路径。

and with that you will have a problem in UWP as normally you don't have the permission. 这样一来,您将在UWP中遇到问题,因为通常情况下您没有权限。 It also won't work here with URI s like: "ms-appdata:///settings.xml" . 它在这里也不适用于URI"ms-appdata:///settings.xml"

Probably you can read a path to your LocalFolder and use it (may work, though haven't tested it), but much easier is to load the content from stream (or read string from file and then load XML from that string), for example like this: 可能您可以读取到LocalFolder的路径并使用它(虽然没有经过测试,它也许可以工作,但可以工作,但更容易的是从流中加载内容(或从文件中读取字符串,然后从该字符串中加载XML),用于像这样的例子:

var file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
using(var stream = await file.OpenStreamForReadAsync())
{
    var doc = XElement.Load(stream);
    // ...
}

Note also that there are other classes like XDocument or XmlDocument where you can load and manage you xml file. 还要注意,还有其他类,例如XDocumentXmlDocument ,您可以在其中加载和管理xml文件。 Everything depends on your needs. 一切都取决于您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM