54

I am having real trouble trying to deserialize some XML and was hoping someone can offer some assistance. I have read a lot of similar posts but I am unable to resolve this.

XML I am attempting to deserialize

<register-account success="false">
  <user-name>xxxxx</user-name>
  <password>fghgh</password>
  <email>test@example.com</email>
  <error>
    <errorcode>120</errorcode>
    <errormessage>The password is invalid</errormessage>
  </error>
</register-account>

Class I am trying to deserialize to:

[Serializable, XmlRoot(ElementName = "register-account", Namespace = "MyNamespace")]
[XmlType("register-account")]
public class RegisterAccountResponse
{
    [XmlAttribute("success")]
    public bool Success { get; set; } 

    /// <summary>
    /// Gets or sets the Tennant email address
    /// </summary>
    [XmlElement("email")]
    public string Email { get; set; }

    /// <summary>
    /// Gets or sets the tennant password
    /// </summary>
    [XmlElement("password")]
    public string Password { get; set; }

    /// <summary>
    /// Gets or sets the Tennant username
    /// </summary>
    [XmlElement("user-name")]
    public string Username { get; set; }

    /// <summary>
    /// A Tenant Portal error relating to the RegisterAccountRequest
    /// </summary>
    [XmlElement("error")]
    public QubeError Error;
}

Deserialization Method

    public static T Deserialize<T>(string data) where T : class
    {
        if (data == null)
        {
            return null;
        }

        if (data.Trim().Length == 0)
        {
            return null;
        }

        var ser = new XmlSerializer(typeof(T));

        using (var sr = new StringReader(data))
        {
            return (T)ser.Deserialize(sr);
        }
    }

Deserialization Method Call

var data = Helper.Deserialize<RegisterAccountResponse>(xml);

Exception:

There is an error in XML document (1, 2). ---> System.InvalidOperationException: was not expected. at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderData.Read5_data()

Inner Exception as follows:

<register-account xmlns=''> was not expected.
ProNotion
  • 3,662
  • 3
  • 21
  • 30

3 Answers3

59

Simply take off the Namespace =:

[XmlRoot("register-account"), XmlType("register-account")]
public class RegisterAccountResponse {...}

since your xml doesn't seem to be in an xml-namespace. Also, [Serializable] isn't used by XmlSerializer.

If your xml was using a namespace it would have an xmlns at the root.

Also, to help with callers you could add where T : class, new() (the , new() being the addition) to your Deserialize method, since XmlSerializer demands a public parameterless constructor.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    Marc you were spot on! I can't thank you enough as I had been tearing my hair out with this one. – ProNotion Feb 03 '11 at 10:51
  • Thank you so much! The extra info on the namespace was the solution I needed. – varagrawal Mar 25 '14 at 12:55
  • Could you please tell more about why the "Namespace =" in the class is needless? – gfan Apr 30 '15 at 06:59
  • @gfan because the xml in the question *does not* include that namespace; the xml and the model/deserializer *need to match*. Specifically, there is no `xmlns="MyNamespace"`, or `xmlns:someAlias="MyNamespace"` – Marc Gravell Apr 30 '15 at 07:16
  • 1
    FYI, this seems to work the opposite way as well. Leaving off the namespace when a namespace is expected resulted in a similar error for me. – Tyler Mar 30 '18 at 16:19
  • 1
    I'm dealing with cXML files that I generated classes via .dtd -> Vidual Studio -> XML -> Create Schema -> xsd.exe /classes. After removing the Namespace Attribute from everything I get a valid object tree. Thanks man – Sebastian Jun 04 '20 at 12:47
2

Nothing worked here for me

What worked is to MAKE SURE that the C# Class (main class) you are trying to map/deserialize the xml string to HAS AN XmlRootAttribute that matches the root element of the response.

Check my full answer with an exmaple https://stackoverflow.com/a/61525536/1594274

Adel Mourad
  • 1,351
  • 16
  • 13
  • 1
    This was my solution also I had `[XmlRoot(ElementName = "RESPONSE")]` instead of `[XmlRoot(ElementName = "response")]` – Myster Sep 22 '20 at 04:01
-2

I found doing the following fixed this for me

if (elem.Attribute(XNamespace.Xmlns + "xsi") == null) {
    elem.Add(new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"));
}

if (elem.Attribute(XNamespace.Xmlns + "xsd") == null) {
    elem.Add(new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema"));
}
GreyCloud
  • 3,030
  • 5
  • 32
  • 47