2

I want to update an XML file status When date is changing

if (DateTime.Parse(dsUpdate.Tables[0].Rows[0][1].ToString()) <= DateTime.Now)
{
    XDocument xDoc = XDocument.Load(fi.FullName);    
    XElement upd = (from doc in xDoc.Descendants("sysInfo")
                    select doc).Single();
    upd.Element("Status").Value = "Updated";
    xDoc.Save(fi.FullName);                           
}

I am using this but somehow it doesn't work.The status of the file is not updated as the date changes. after loading the file it jumps to the catch block and nothing happen the status remains the same.

This is the XML file I am using:

<?xml version="1.0" encoding="utf-8"?>
<System>
    <SysInfo>
        <InstallDate>2/11/2015 2:26:21 PM</InstallDate>
        <UpdateDate>2/12/2015 2:26:21 PM</UpdateDate>
        <Status>Installed</Status>
    </SysInfo>
</System>
6
  • 2
    "it jumps to the catch block" - well, what exception got thrown?
    – Corak
    Feb 9, 2015 at 9:54
  • 1
    Additionally, (from doc in xDoc.Descendants("sysInfo") select doc).Single(); would be more clearly written as just xDoc.Descendants("sysInfo").Single(). You don't have to write a query expression...
    – Jon Skeet
    Feb 9, 2015 at 9:57
  • post the XML file you are using. You probably have more than one element with name "sysInfo" or that element has no child called "Status".
    – helb
    Feb 9, 2015 at 9:57
  • sequence contains no element Feb 9, 2015 at 9:57
  • <?xml version="1.0" encoding="utf-8"?> <System> <SysInfo> <InstallDate>2/11/2015 2:26:21 PM</InstallDate> <UpdateDate>2/12/2015 2:26:21 PM</UpdateDate> <Status>Installed</Status> </SysInfo> </System> Feb 9, 2015 at 9:58

1 Answer 1

2

Element names are case-sensitive. Use

XElement upd = (from doc in xDoc.Descendants("SysInfo")
                select doc).Single();

Or as proposed by @JonSkeet :

XElement upd = xDoc.Descendants("SysInfo").Single();
3
  • Same exception again Feb 9, 2015 at 10:03
  • 1
    @AnoopMishra Did you post your entire xml file? Or did you remove some namespaces? There must be something else going on. Are you sure you open the right file?
    – helb
    Feb 9, 2015 at 10:06
  • sorry the problem is in tag SysInfo I am using wrong tag Feb 9, 2015 at 10:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.