XML : Looking for help finding an element in an XML XDocument and updating attributes

I am learning about XML queries and Xdocuments and am having trouble updating an existing element's attributes. This is my WCF service. The second part works(creating the new element with attributes. The problem is that my query must not be returning any results and the code always adds a new element.

          //this will insert the officer location and status into the xml data file      //I read about how to do this at http://prathapk.net/creating-wcf-service-to-store-read-data-in-xml-database/      //and https://msdn.microsoft.com/en-us/library/bb387041.aspx      public void InsertOfficerData(string OfficerID, double latitude, double longitude, int StatusCode)      {          //open xml file          XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("Officers.xml"));          //linq query to find the element with the officer ID if it exists          IEnumerable<XElement> officer =              from el in doc.Element("Officers").Elements("Officer")              where (string)el.Attribute("OfficerID") == OfficerID              select el;            bool updated = false;          //update officer attributes          foreach (XElement el in officer)          {              //update attributes              el.Attribute("Latitude").Value = Convert.ToString(latitude);              updated = true;              doc.Save(HttpContext.Current.Server.MapPath("Officers.xml"));          }          //if an officer with the id was not found          if (!updated)          {              //add the element with attributes              doc.Element("Officers").Add(new XElement("Officer",                  new XAttribute("ID", OfficerID),                  new XAttribute("Latitude", latitude),                  new XAttribute("Longitude", longitude),                  new XAttribute("Status", StatusCode)));              doc.Save(HttpContext.Current.Server.MapPath("Officers.xml"));          }        }    

Sample of my XML file structure:

  <?xml version="1.0" encoding="utf-8"?>  <Officers>    <Officer ID="Dust" Latitude="4" Longitude="5" Status="3" />  </Officers>  

No comments:

Post a Comment