Posted By

darkbaron1912 on 02/27/11


Tagged

xml Linq


Versions (?)

linq xml


 / Published in: C#
 

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Patients>
  3. <Patient EMail="[email protected]">
  4. <FirstName>LeBron</FirstName>
  5. <LastName>James</LastName>
  6. </Patient>
  7. <Patient EMail="[email protected]">
  8. <FirstName>Kobe</FirstName>
  9. <LastName>Bryant</LastName>
  10. </Patient>
  11. <Patient EMail="[email protected]">
  12. <FirstName>Allen</FirstName>
  13. <LastName>Iverson</LastName>
  14. </Patient>
  15. </Patients>
  16.  
  17.  
  18. class PatietList : List<Patient>
  19. {
  20. public void Load(string xmlFile)
  21. {
  22. XDocument doc = XDocument.Load(xmlFile);
  23.  
  24. var query = from xElem in doc.Descendants("Patient")
  25. select new Patient
  26. {
  27. EMail = xElem.Attribute("EMail").Value,
  28. FirstName = xElem.Element("FirstName").Value,
  29. LastName = xElem.Element("LastName").Value,
  30. };
  31.  
  32. this.Clear();
  33. AddRange(query);
  34. }
  35.  
  36. public void Save(string xmlFile)
  37. {
  38. XElement xml = new XElement("Patients",
  39. from p in this
  40. select new XElement("Patient",
  41. new XAttribute("EMail", p.EMail),
  42. new XElement("FirstName", p.FirstName),
  43. new XElement("LastName", p.LastName)));
  44.  
  45. xml.Save(xmlFile);
  46.  
  47. }
  48.  
  49. }

Report this snippet  

You need to login to post a comment.