0

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.

Martin Valentino
  • 1,002
  • 2
  • 11
  • 26
  • Take a look at [XNamespace](https://msdn.microsoft.com/en-us/library/vstudio/system.xml.linq.xnamespace(v=vs.100).aspx) – Tim Jun 17 '15 at 23:54
  • possible duplicate of [Use Linq to Xml with Xml namespaces](http://stackoverflow.com/questions/2340411/use-linq-to-xml-with-xml-namespaces) – Tim Jun 17 '15 at 23:56
  • 1
    The second fragment is not valid Xml. It does not have a namespace - you have a prefix that is not bound to any namespace. – Pawel Jun 17 '15 at 23:56
  • The thing is that xml string works in IOS code. They can parse it back to objective-c object. But when I look at the code, I can't find a similar function in C# – Martin Valentino Jun 17 '15 at 23:58
  • 1
    @MartinSiagian - Does the iOS code have a mapping for the namespace prefix `te` somewhere? – Tim Jun 18 '15 at 00:08

1 Answers1

0

you can use XmlSerializer and call the Deserialize method

var x = new XmlSerializer (typeof(MyStronglyType));
MyStronglyType m = (MyStronglyType) x.Deserialize(myStream);