Skip to content

Instantly share code, notes, and snippets.

@Dynyx
Created June 4, 2012 13:20
Show Gist options
  • Save Dynyx/2868329 to your computer and use it in GitHub Desktop.
Save Dynyx/2868329 to your computer and use it in GitHub Desktop.
LINQ2XML example
<?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