Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize an XML doc with a prefixed namespace but no ns-prefixed elements?

I have an XML document from an external source.

<?xml version="1.0" encoding="utf-8"?>
<ns0:Info xmlns:ns0="http://www.ZomboCorp.com/">
  <Name>Anthony</Name>
  <Job>Developer</Job>
</ns0:Info>

I need to deserialize it into an object like this.

public class Info
{
    public String Name { get; set; }
    public String Job { get; set; }
}

Used as is, the Serializer throws an InvalidOperationException

<Info xmlns='http://www.ZomboCorp.com/'> was not expected.

If I add [XmlElement(Namespace = "http://www.ZomboCorp.com/")] to the class definition, the Serializer returns a new Info object with null properties.

like image 551
Anthony Mastrean Avatar asked Sep 05 '25 03:09

Anthony Mastrean


2 Answers

You have to add the XmlElement attribute to each property as well, setting the Namespace property to an empty string (as the namespace is not inherited in your situation).

Your definition for Info should look like this:

XmlRoot(Namespace = "http://www.ZomboCorp.com/")]
public class Info
{
    [XmlElement(Namespace = "")]
    public String Name { get; set; }
    [XmlElement(Namespace = "")]
    public String Job { get; set; }
}

Then it will deserialize correctly.

like image 186
casperOne Avatar answered Sep 07 '25 21:09

casperOne


I used xsd.exe (a VS tool) and generated a schema from the XML file and then a class file from the schema. It suggested

[XmlType(AnonymousType = true, Namespace = "http://www.ZomboCorp.com/")]
[XmlRoot(Namespace = "http://www.ZomboCorp.com/", IsNullable = false)]
public class Info
{
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Name { get; set; }
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Job { get; set; }
}

But, I was able to get away with

[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "http://www.ZomboCorp.com/")]
public class Info
{
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Name { get; set; }
    [XmlElement(Form = XmlSchemaForm.Unqualified)]
    public String Job { get; set; }
}
like image 20
Anthony Mastrean Avatar answered Sep 07 '25 19:09

Anthony Mastrean