Currently working on a wp7 App, its quite basic. the user has a counter and if a date element exists for the current day in an XML file the count is updated, if not a new date element is created for that day and with the count as the value.
My priblem is, all is working fine if a new XML file is created, the current date element is updated no problem, but if I test the following day, a new element is created, but when I want to update the count, a new date element is added. I don’t get this as all the code works on a new file, but if the file is a day old its not for some reason.
XML code
<?xml version="1.0" encoding="utf-8"?>
<Countlog>
<date Count="9">4/21/2012</date>
<date Count="4">4/21/2012</date>
<date Count="18">4/21/2012</date>
</Countlog>
C#
private void save_btn_Click(object sender, RoutedEventArgs e)
{
String _count = Count_tb.Text;
String s_todaysdate = todaysdate.Date.ToShortDateString();
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("Countlog.xml", FileMode.Open, myIsolatedStorage);
StreamReader reader = new StreamReader(isoStream);
XDocument _xml = XDocument.Load(reader);
isoStream.Close();
var query = from r in _xml.Descendants("Countlog")
where r.Element("date").Value == (DateTime.Now.ToShortDateString())
select r.Element("date");
if (!query.Any())
{
XElement Addnewdate = new XElement("date", s_todaysdate, new XAttribute("Count", _count));
_xml.Root.Add(Addnewdate);
MessageBox.Show("no matching date");
}
else
{
foreach (XElement _date in query)
{
_date.Attribute("Count").Value = _count.ToString();
MessageBox.Show("Updating date");
}
}
IsolatedStorageFileStream isoStreamsave = new IsolatedStorageFileStream("Countlog.xml", FileMode.Truncate, myIsolatedStorage);
_xml.Save(isoStreamsave);
isoStreamsave.Close();
}
private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (pivotholder.SelectedIndex == 1)
{
IsolatedStorageFileStream isoFileStream2 = myIsolatedStorage.OpenFile("Countlog.xml", FileMode.Open);
StreamReader reader = new StreamReader(isoFileStream2);
XML_result.Text = reader.ReadToEnd();
reader.Close();
}
}
Please let me know if you need more info, This is my first time posting here after lurking around for the past few years.
Cheers
Jon
Okay, I’ve worked it out. This query:
will only match if the first
dateelement has the right value. You’re iterating over allCountlogelements (of which there’s only one), and looking for the firstdateelement (because that’s whatElement(...)does).You could change this to use simply:
However, I would suggest an alternative format to start with:
Then to add a new element:
Or to update one:
This uses the data-type handling of LINQ to XML, instead of converting everything to strings explicitly.