I’m creating a windows phone 7 app and I’m having a bit of a trouble with changing values in my xml-file, which is located inside isolated storage.
My method is here:
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);
}
}
}
}
And my xml-file inside isolated storage looks like this:
<?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>
I get a NullReferenceException from this line:
xml.Root.Attribute(itemAttribute).SetValue(value);
Any ideas how I should do it then?
Cheers.
You’re using
xml.Root.Attributein your loop which is trying to find the attribute on the root element – where it doesn’t exist. You’re also completely ignoring theivariable in your iterator.I think you meant:
Note that by using the explicit conversion from
XAttributetostringin the query, there won’t be an exception if there are anyitemelements which don’t have theidattribute.It’s worth noting that this has nothing to do with Windows Phone 7 or isolated storage really – you’d get exactly the same error with your original code using the desktop framework from a console app, even with the XML hard-coded. For similar situations, it’s worth trying to reproduce and debug the problem in a desktop setting, as it’s typically quicker than using the emulator or a real device.