Geeks With Blogs
Ben Adler's Development Posting solutions as I find them
Here is a handy method that accepts an XElement and an object. It loops through each attribute in the XML element and sets the matching property on the object:

        public static object SetProperties(object obj, XElement xelement)
        {
            foreach (var attribute in xelement.Attributes()) //loop through attributes of element
            {
                PropertyInfo propertyInfo = obj.GetType().GetProperty(attribute.Name.ToString()); //get property that matches attribute

                //make sure property exists
                if (propertyInfo != null)
                {
                    if (propertyInfo.PropertyType == typeof(int) || propertyInfo.PropertyType == typeof(int?)) //int
                        propertyInfo.SetValue(obj, int.Parse(attribute.Value), null);
                    else if (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?)) //datetime
                        propertyInfo.SetValue(obj, DateTime.Parse(attribute.Value), null);
                    else //string
                        propertyInfo.SetValue(obj, attribute.Value, null);
                }
            }

            return obj;
        }
Posted on Tuesday, September 16, 2014 9:39 AM C# , XML , XElement | Back to top


Comments on this post: Loop through XML Element and set dynamic properties on object

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © BenAdler | Powered by: GeeksWithBlogs.net