2

I'm trying to deserialize an XML stream and getting the following error:

Error in line 1 position 7. Expecting element 'auth' from namespace 'http://schemas.datacontract.org/2004/07/Veracross'.. Encountered 'Element' with name 'auth', namespace ''.

The XML stream I'm deserializing looks like this:

<auth>
    <status>success</status>
    <username>jsmith</username>
    <person_pk>1234</person_pk>
    <security_roles>Parent</security_roles>
</auth>

My code:

[DataContract(Name = "auth")]
public class Authorization
{
    [DataMember(Name = "status")]
    public string Status { get; set; }
    [DataMember(Name = "username")]
    public string UserName { get; set; }
    [DataMember(Name = "security_roles")]
    public string SecurityRoles { get; set; }
}

// Some code here receiving the XML and storing in a string (xmlData)

DataContractSerializer serializer = new DataContractSerializer(typeof(Authorization));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));
Authorization Auth = (Authorization)serializer.ReadObject(stream);

I presume it's not happy with the barebones XML file (no header info) but I don't have any control over it. It is consumed from a RESTful service.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BKahuna
  • 601
  • 2
  • 11
  • 23
  • Looks like its expecting an element auth with a namespace of 'http://schemas.datacontract.org/2004/07/Veracross' but its finding auth without any namespace. I am not sure where the error is coming from you might need to add a namespace to a parser or something along those lines. – Dan675 Feb 24 '12 at 21:39
  • 1
    Thanks I tried decorating the auth class definition with: [DataContract (Namespace = "http://schemas.datacontract.org/2004/07/Veracross", Name = "auth"] but the error is just the same. – BKahuna Feb 24 '12 at 23:53
  • I prefaced the Namespace with "http://" and it doesn't end with a semi-colon - SO is screwing up my comment. – BKahuna Feb 24 '12 at 23:57

1 Answers1

0

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

I solved the problem by modifying the xmlData string a little.

string xmlData = client.DownloadString(restURL);
string fixedXMLData = xmlData.Replace("<auth>", "<auth xmlns=\"http://schemas.datacontract.org/2004/07/Veracross\">");
DataContractSerializer serializer = new DataContractSerializer(typeof(Authorization));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(fixedXMLData));

By adding the namespace it expected manually everything worked.

Community
  • 1
  • 1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129