I need to parse an XML string to c# object. I can parse it using LINQ to XML function if it's the valid XML like
<root>
<child1>item on child1</child1>
<child2>item on child2</child2>
</root>
The way I parse it to object is:
public static T Deserialize<T>(string xml, string elementName)
{
var xDoc = XDocument.Parse(xml);
var x = xDoc.Element(elementName);
var result = Activator.CreateInstance<T>();
foreach (var node in x.Elements())
{
if (node.Elements().Any())
{
continue;
}
var properties = typeof(T).GetProperties();
var property = properties.SingleOrDefault(p => p.Name == node.Name.LocalName);
property = property ?? properties.SingleOrDefault(p => p.IsDefined(typeof(XmlElementAttribute), false) && ((XmlElementAttribute)Attribute.GetCustomAttribute(p, typeof(XmlElementAttribute))).ElementName == node.Name.LocalName);
if (property == null)
{
continue;
}
property.SetValue(result, Convert.ChangeType(node.Value, property.PropertyType));
}
return result;
}
But I can't use the same method if the XML string has custom namespace like:
<te:array>
<te:v>tumper</te:v>
<te:v>gottag?</te:v>
<te:v>f</te:v>
</te:array>
I don't know if there is any method that I can use to parse the custom namespace, all of the help would be really helpful.