XmlNode to Entity?

Jul 6, 2010 at 1:37 PM


Is it possible to map Xml data to an Entity object?

Something like this:

public static List<Plant> TestData
        XmlDocument xmlDoc = new XmlDocument();
        List<Plant> data = new List<Plant>();

        foreach (XmlNode plantNode in xmlDoc.SelectNodes("catalog/plant"))
            Plant plant = new Plant();

            plant.Common = plantNode.SelectSingleNode("common").InnerText;
            plant.Botanical = plantNode.SelectSingleNode("botanical").InnerText;
            plant.Zone = plantNode.SelectSingleNode("zone").InnerText;
            plant.ColorCode = plantNode.SelectSingleNode("colorCode").InnerText;
            plant.Light = plantNode.SelectSingleNode("light").InnerText;
            plant.Price = decimal.Parse(plantNode.SelectSingleNode("price").InnerText, culture);
            plant.Availability = DateTime.Parse(plantNode.SelectSingleNode("availability").InnerText, culture);
            plant.Indoor = bool.Parse(plantNode.SelectSingleNode("indoor").InnerText);


        return data;


Jul 6, 2010 at 3:13 PM
Edited Jul 6, 2010 at 4:01 PM

yes it is, too bad I'm not very familiar with the xml stuff, but with the help of intellisense I came up with this injection

        public class XmlNodeToObject : KnownSourceValueInjection<XmlNode>
            protected override void Inject(XmlNode source, object target, PropertyDescriptorCollection targetProps)
                for (int i = 0; i < targetProps.Count; i++)
                    var t = targetProps[0];
                    object value = null;

                    if (t.PropertyType == typeof(string))
                        value = source.SelectSingleNode(t.Name.ToLower()).InnerText;

                    if (t.PropertyType == typeof(bool))
                        value = bool.Parse(source.SelectSingleNode(t.Name.ToLower()).InnerText);

                    if (value != null)
                        t.SetValue(target, value);
at the moment it takes all properties of type string and bool from the target object and looks for a selectsinglenode with the name of that property in lower case,
and sets its value (although it doesn't check if that node actually exist, but it should somehow, probably that doesn't matter) 
hope it helps, cya
Feb 18, 2011 at 10:20 AM

Hi again,

Currently I am at version 2.1 of ValueInjecter.

Is this sample code still valid or is there some pre-build injection class to perform this?

Thanks in advance,


Feb 18, 2011 at 6:40 PM

it's still valid