如何在Windows Phone xap部署中包含XML数据?

时间:2010-08-23 01:19:04

标签: silverlight windows-phone-7 xap

我正在开发WP7应用程序。该应用程序将有几个XML文件。有些是读写,有些是只读的。我有什么选择? IsolatedStorage?嵌入资源?

我还需要知道......

  1. 如何将XML加载到XElements中?
  2. 如何将XElement保存到其中?

2 个答案:

答案 0 :(得分:2)

对于写访问,您需要使用IsolatedStorage。您可以检查文件是否存在并从IsolatedStorage加载它,否则从资源加载它。对于只读访问,您只需从资源加载即可。将xml文件添加到项目中检查Build Action is Content。

XDocument doc = LoadFromIsolatedStorage(name);
if (doc == null)
{
    doc = LoadFromResource(name);
}

////////////////////////////

public static XDocument LoadFromResource(string name)
{
    var streamInfo = Application.GetResourceStream(new Uri(name, UriKind.Relative));
    using(var s = streamInfo.Stream)
        return XDocument.Load(s);

}

public static XDocument LoadFromIsolatedStorage(string name)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(name))
        {
            using(var stream = store.OpenFile(name,FileMode.Open))
                return XDocument.Load(stream);
        }
        else
            return null;
    }
}

public static void SaveToIsolatedStorage(XDocument doc, string name)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        var dir = System.IO.Path.GetDirectoryName(name);
        if (!store.DirectoryExists(dir))
            store.CreateDirectory(dir);
        using (var file = store.OpenFile(name, FileMode.OpenOrCreate))
            doc.Save(file);
    }
}

答案 1 :(得分:0)

只是想一想,你想把“xap”作为一个包含所有文件的“exe”吗?如果是这样,您可以使用工具Desklighter(http://blendables.com/labs/desklighter/)。