How can I use a class as a data model when querying an XDocument?

I have an Xml document:

<?xml version="1.0" encoding="utf-8"?> <Family xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Person member="father" id="0"> <Surname>Smith</Surname> <Forename>Robert</Forename> <Person member="son" id="1"> <Surname>Smith</Surname> <Forename>Sam</Forename> <Person member="son" id="2"> <Surname>Smith</Surname> <Forename>Jeff</Forename> </Person> </Person> <Person member="daughter" id="3"> <Surname>Smith</Surname> <Forename>Sarah</Forename> </Person> </Person> </Family> 

... and a few helper classes:

  [XmlRoot] public class Family { [XmlElement] public List<Person> Person; } public class Person { [XmlAttribute("member")] public MemberType Member { get; set; } [XmlAttribute("id")] public int Id { get; set; } [XmlElement] public string Surname { get; set; } [XmlElement] public string Forename { get; set; } [XmlElement("Person")] public List<Person> People; } public enum MemberType { Father, Mother, Son, Daughter } 

Now, let's say Family has a method defined as such:

 public IEnumerable<Person> Find (Func<Person, bool> predicate) { // also, I know that this SelectMany will not work - assume this foreach works // on a flattened list of people foreach (var p in family.Person.SelectMany()) { if(predicate(p)) { yield return p; } } } 

... but I don't want to deserialize Xml for the Family and Person classes. I would just like to download the XDocument and the request directly, but working with XElement, XAttribute and XName is not that friendly when providing the API. I understand that I need classes - Family and Person - but they are just models.

Can I find the Find method where I can pass something like:

 IEnumerable<Person> people = someBusinessObj.Find(p => p.Forename == "Jeff"); 

Update
I would prefer a solution that is not related to an open source project (as @MartinHonnen mentions).

+1
source share
1 answer

Why don't you want to deserialize XML into objects? This will give you exactly the software interface you need. I'd:

All this requires very little effort to implement!

+1
source

All Articles