我有一个Xml文档:
<?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>
......以及一些支持类如下:
[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
}
现在,说Family
有一个定义如下的方法:
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;
}
}
}
...但我不想将反序列化 Xml到Family
和Person
类。我想简单地加载XDocument并直接查询 - 但是在提供API时使用XElement,XAttribute和XName并不友好。我意识到我需要课程 - Family
&amp; Person
- 但它们只是模特。
我可以使用Find方法传递类似的内容:
IEnumerable<Person> people = someBusinessObj.Find(p => p.Forename == "Jeff");
更新
我更喜欢不涉及开源项目的解决方案(如@MartinHonnen所述)。
答案 0 :(得分:1)
为什么不想将XML反序列化为对象?这将为您提供所需的编程接口。我会:
这一切只需要很少的努力就可以实现!