XElement MapFromContact(Contact contact) { var elem = new XElement( "Contact", new XAttribute("Id", contact.Id), new XElement("FirstName", contact.FirstName), new XElement("LastName", contact.LastName), new XElement("Email", contact.Email) ); var nicknames = new XElement("Nicknames"); foreach (var nickname in contact.Nicknames) nicknames.Add(new XElement("Nickname", nickname)); elem.Add(nicknames); return elem; }
private XElement GetContactNode(XDocument doc, Contact contact) { return doc.Descendants("Contact").Single(node => node.Attribute("Id").Value == contact.Id.ToString()); }
public void Insert(Contact contact) { var fileName = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Contacts.xml"); var xdoc = XDocument.Load(fileName); contact.Id = xdoc.Descendants("Contact").Max(node=> (int)node.Attribute("Id")) + 1; xdoc.Descendants("Contacts").First().Add(MapFromContact(contact)); xdoc.Save(fileName); }
public Contact GetContact(int id) { var xdoc = XDocument.Load(XmlFile); var contact = new Contact {Id = id }; var node = GetContactNode(xdoc, contact); return MapToContact(node); }
public void Edit(Contact contact) { var doc = XDocument.Load(XmlFile); var nodeToReplace = GetContactNode(doc, contact); nodeToReplace.ReplaceWith(MapFromContact(contact)); doc.Save(XmlFile); }
public void Delete(Contact contact) { var doc = XDocument.Load(XmlFile); var nodeToDelete = GetContactNode(doc, contact); nodeToDelete.Remove(); doc.Save(XmlFile); }