2011-12-17 61 views
0

我正在创建一个Windows Phone 7应用程序,并且在更改xml文件(位于独立存储内部)中的值时遇到了一些问题。 我的方法是在这里:如何修改存储在独立存储器内的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); 

任何想法如何那我该怎么做? 干杯。

回答

2

您正在使用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); 
} 

注意通过在查询中使用从XAttribute明确转化为string,不会有异常,如果有不具备任何item元素id属性。

值得注意的是,这与Windows Phone 7或独立存储真的没有任何关系 - 即使使用硬编码的XML,使用桌面框架从控制台应用程序获得与原始代码完全相同的错误。对于类似的情况,值得在桌面设置中重现和调试问题,因为它通常比使用仿真器或真实设备更快。

+0

是的,它似乎工作。我不知道我在那里有什么样的脑冻结。谢谢。 – Baburo 2011-12-18 17:14:12