Search code examples
c#xmlxml-serialization

XmlSerializer crashes when encountering xml attribute (namespace)


Im trying to Deserialize a XML im getting from a service. But the XmlSerializer failes when encountering the first attribute.

My shortened xml looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:basicInformation xmlns:ns2="http://fu.bar.com/">
   <somenode>...</somenode>
   ...
</ns2:basicInformation>

My class looks like this

[XmlRoot(ElementName = "basicInformation")]
public class BasicInformation
{
  [XmlElement(ElementName = "somenode")]
  public string SomeNode { get; set; }

  ...

  [XmlAttribute(AttributeName = "ns2")]
  public string Ns2 { get; set; }

  [XmlText]
  public string Text { get; set; }
}

The error i get is this:

"There is an error in XML document (1, 57)."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233079
HelpLink: null
InnerException: {"<basicInformation xmlns='http://message.async.dms.svap.deere.com/'> was not expected."}
Message: "There is an error in XML document (1, 57)."
Source: "System.Xml"
StackTrace: "   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)\r\n   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)\r\n   at AzureQueue.Program.Blurg() in E:\\_Code_\\Testing\\AzureQueue\\AzureQueue\\Program.cs:line 432\r\n   at AzureQueue.Program.<DoSomething>d__1.MoveNext() in E:\\_Code_\\Testing\\AzureQueue\\AzureQueue\\Program.cs:line 71"
TargetSite: {System.Object Deserialize(System.Xml.XmlReader, System.String, System.Xml.Serialization.XmlDeserializationEvents)}

If I replace the second line in the xaml from this:

<ns2:basicInformation xmlns:ns2="http://fu.bar.com/">

to this:

<basicInformation>

everything works just fine.

So it's something with that attribute that im not handeling correctly, but I haven't been able to find a solution.

I should mention that the C# class was generated from a xml to c# tool because the full xml is huge.

So what am I missing? I could solve this the really ugly way and do a string replace but that feels very wrong! ;)

Update

I have accepted @Marc Gravell answer, it works. But i choose to go with the @Denis Micheal solution because it solves my my problem without having to put namespaces on all the XML nodes in my c# models


Solution

  • [XmlRoot(ElementName = "basicInformation", Namespace = "http://fu.bar.com/")]
    public class BasicInformation
    

    Your data is namespace-qualified, and that matters. You may need to apply this individually to child elements, too, but: take that as it comes.