Question

I have an xml similar to his one

<ns2:person xmlns:ns2="somenamespace">
  <firstName>John</firstName>
  <lastName>John</lastName>
</ns2:person>

I try to deserialize it like this:

var ser = new XmlSerializer(typeof(Person));
b = (Person)ser.Deserialize(new StringReader(xml));

T is a class

[XmlRoot(Name = "person", Namespace = "somenamespace")]
public class Person {
    [XmlElement(ElementName = "firstName")]
    public string fistName {get;set;}
    [XmlElement(ElementName = "lastName")]
    public string lastName {get;set;}
}

after the creation of the object it's properties remain null

the same example works if you remove the schema like <person>...

Unfortunately I cannot control the source xml, I need to understand the reason behind and find out a workaround besides altering the xml string (if there is one).

Was it helpful?

Solution

Add Namespace = "" to XmlElement attribute

[XmlRoot(ElementName = "person", Namespace = "somenamespace")]
public class Person {
  [XmlElement(ElementName = "firstName", Namespace = "")]
  public string fistName { get; set; }
  [XmlElement(ElementName = "lastName", Namespace = "")]
  public string lastName { get; set; }
}    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top