我正在尝试反序列化XML流并收到以下错误:
第1行位置出错7.期望来自命名空间“http://schemas.datacontract.org/2004/07/Veracross”的元素'auth'。遇到名为'auth'的'Element',名称空间''。
我正在反序列化的XML流看起来像这样:
<auth>
<status>success</status>
<username>jsmith</username>
<person_pk>1234</person_pk>
<security_roles>Parent</security_roles>
</auth>
我的代码:
[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);
我认为它对准系统XML文件(没有标题信息)不满意,但我对它没有任何控制权。它来自RESTful服务。
答案 0 :(得分:0)
(在问题编辑中由OP回答。转换为社区维基答案。请参阅Question with no answers, but issue solved in the comments (or extended in chat))
OP写道:我通过修改xmlData字符串解决了这个问题。
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));
通过添加命名空间,它手动预期一切正常。