2011-12-17 8 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ファイルは次のようになります。私はこのラインからとNullReferenceExceptionを取得

<?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> 

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); 
} 

注持たないitem要素がある場合は、クエリでstringXAttributeから明示的な変換を使用することにより、例外がないことid属性。

Windows Phone 7や隔離されたストレージとはまったく関係がありません。コンソールアプリケーションからのデスクトップフレームワークを使用して元のコードとまったく同じエラーが発生します。 。同様の状況では、エミュレータや実​​際のデバイスを使用するよりも通常は速いので、デスクトップ設定で問題を再現してデバッグすることをお勧めします。

+0

うん、それはうまくいくようです。私はそこにいた脳の凍結がどんなものか不思議です。ありがとう。 – Baburo

関連する問題