Created
June 4, 2012 13:20
-
-
Save Dynyx/2868329 to your computer and use it in GitHub Desktop.
LINQ2XML example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<Patients> | |
<Patient EMail="[email protected]"> | |
<FirstName>LeBron</FirstName> | |
<LastName>James</LastName> | |
</Patient> | |
<Patient EMail="[email protected]"> | |
<FirstName>Kobe</FirstName> | |
<LastName>Bryant</LastName> | |
</Patient> | |
<Patient EMail="[email protected]"> | |
<FirstName>Allen</FirstName> | |
<LastName>Iverson</LastName> | |
</Patient> | |
</Patients> | |
class PatietList : List<Patient> | |
{ | |
public void Load(string xmlFile) | |
{ | |
XDocument doc = XDocument.Load(xmlFile); | |
var query = from xElem in doc.Descendants("Patient") | |
select new Patient | |
{ | |
EMail = xElem.Attribute("EMail").Value, | |
FirstName = xElem.Element("FirstName").Value, | |
LastName = xElem.Element("LastName").Value, | |
}; | |
this.Clear(); | |
AddRange(query); | |
} | |
public void Save(string xmlFile) | |
{ | |
XElement xml = new XElement("Patients", | |
from p in this | |
select new XElement("Patient", | |
new XAttribute("EMail", p.EMail), | |
new XElement("FirstName", p.FirstName), | |
new XElement("LastName", p.LastName))); | |
xml.Save(xmlFile); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment