Created
July 16, 2012 03:08
-
-
Save rebornix/3120198 to your computer and use it in GitHub Desktop.
ConvertToXml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static XmlDocument ToXml(object thisObj) | |
{ | |
XmlDocument propertyDoc = new XmlDocument(); | |
XmlNode rootNode = propertyDoc.CreateElement(thisObj.GetType().Name.Replace("[]", "Array")); | |
propertyDoc.AppendChild(rootNode); | |
if (thisObj.GetType().IsArray) | |
{ | |
Array objects = (Array)thisObj; | |
foreach (object obj in objects) | |
{ | |
rootNode.AppendChild(propertyDoc.ImportNode(ToXml(obj).SelectSingleNode("/*"), true)); | |
} | |
return propertyDoc; | |
} | |
PropertyInfo[] properties = thisObj.GetType().GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.GetProperty); | |
if (properties.Length == 0 || thisObj.GetType().IsValueType || thisObj.GetType() == typeof(string)) | |
{ | |
XmlNode propertyNode = propertyDoc.CreateNode("element", thisObj.GetType().Name, string.Empty); | |
rootNode.InnerText = thisObj.ToString(); | |
return propertyDoc; | |
} | |
foreach (PropertyInfo property in properties) | |
{ | |
if (property.PropertyType.IsArray) | |
{ | |
XmlNode propertyArrayNode = propertyDoc.CreateNode("element", property.Name, string.Empty); | |
rootNode.AppendChild(propertyArrayNode); | |
object arrayObj = property.GetValue(thisObj, null); | |
Array objects = (Array)arrayObj; | |
if (objects != null) | |
{ | |
foreach (object obj in objects) | |
{ | |
try | |
{ | |
propertyArrayNode.AppendChild(propertyDoc.ImportNode(ToXml(obj).SelectSingleNode("/*"), true)); | |
} | |
catch (Exception) | |
{ | |
XmlNode propertyNode = propertyDoc.CreateNode("element", obj.GetType().Name, string.Empty); | |
propertyNode.InnerText = obj.ToString(); | |
propertyArrayNode.AppendChild(propertyNode); | |
} | |
} | |
} | |
} | |
else | |
{ | |
XmlNode propertyNode = propertyDoc.CreateNode("element", property.Name, string.Empty); | |
object obj = property.GetValue(thisObj, null); | |
if (obj == null) | |
{ | |
propertyNode.InnerText = string.Empty; | |
} | |
else | |
{ | |
propertyNode.InnerXml = ToXml(obj).SelectSingleNode("/*").InnerXml; | |
} | |
rootNode.AppendChild(propertyNode); | |
} | |
} | |
return propertyDoc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment