Creates xml to object

//setup xml
var xmls = @"
<user>
   <id>1</id>
   <name>George</name>
</user>";
var doc = new XmlDocument();
doc.LoadXml(xmls);

//Create "george"  User object from children elements
var george = doc.DocumentElement.ChildrenToObject<User>(); 

//setup xml
xmls = @"<user id=""1"" name=""john"" />";
doc = new XmlDocument();
doc.LoadXml(xmls);

//Create "john"  User object from attributes
var john = doc.DocumentElement.AttributesToObject<User>(); 

public class User:IEquatable<User>
{
public int Id { get; set; }
public string Name { get; set; }
public bool Equals(User other)
{
	return Id == other.Id;
}
}

Discussion
As you see it's very easy to parse xml into objects, it is very useful when working with xml configuration. You can also use ChildrenToDictionary or AttributesToDictionary methods if they are better suited for your case.

Last edited Jan 21, 2011 at 7:47 AM by mike_sapiens, version 4

Comments

No comments yet.