【问题标题】:How do I modify a value in xml file stored inside isolated storage?如何修改存储在隔离存储中的 xml 文件中的值?
【发布时间】:2011-12-17 13:52:44
【问题描述】:

我正在创建一个 Windows Phone 7 应用程序,但在更改位于隔离存储内部的 xml 文件中的值时遇到了一些麻烦。 我的方法在这里:

public void updateItemValueToIsoStorage(string id, 
                                        string itemAttribute, 
                                        string value)
{
    using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (var stream = isoStorage.OpenFile(
                           "items.xml", FileMode.Open, FileAccess.ReadWrite))
        {
            XDocument xml = XDocument.Load(stream, LoadOptions.None);
            //According to given parameters, 
            //set the correct attribute to correct value.
            var data = from c in xml.Descendants("item")
                       where c.Attribute("id").Value == id
                       select c;
            foreach (Object i in data) 
            {

                xml.Root.Attribute(itemAttribute).SetValue(value);

            }                
        }
    }
}

我在隔离存储中的 xml 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<items>
<item id="0" title="Milk" image="a.png" lastbought="6" lastingtime="6" />
<item id="1" title="Cheese" image="b.png" lastbought="2" lastingtime="20" />
<item id="2" title="Bread" image="c.png" lastbought="3" lastingtime="8" />
</items>

我从这一行得到一个 NullReferenceException:

xml.Root.Attribute(itemAttribute).SetValue(value);

有什么想法我应该怎么做吗? 干杯。

【问题讨论】:

    标签: xml windows-phone-7 nullreferenceexception


    【解决方案1】:

    您在循环中使用xml.Root.Attribute,它试图在根元素上查找属性——它不存在。您还完全忽略了迭代器中的 i 变量。

    我想你的意思是:

    var data = from c in xml.Descendants("item")
               where (string) c.Attribute("id") == id
               select c;
    
    foreach (XElement element  in data)
    {
        element.Attribute(itemAttribute).SetValue(value);
    }
    

    请注意,通过在查询中使用从XAttributestring 的显式转换,如果有任何item 元素不具有id 属性,则不会出现异常。

    值得注意的是,这实际上与 Windows Phone 7 或独立存储无关 - 使用控制台应用程序中的桌面框架的原始代码会得到完全相同的错误,即使使用 XML 硬编码也是如此。对于类似情况,值得尝试在桌面设置中重现和调试问题,因为它通常比使用模拟器或真实设备更快。

    【讨论】:

    • 是的,它似乎正在工作。我想知道我在那里经历了什么样的大脑冻结。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多