我在将“声明了 2 个命名空间的 xml 字符串”反序列化为对象时遇到了同样的错误。
<?xml version="1.0" encoding="utf-8"?>
<vcs-device:errorNotification xmlns:vcs-pos="http://abc" xmlns:vcs-device="http://def">
<errorText>Can't get PAN</errorText>
</vcs-device:errorNotification>
[XmlRoot(ElementName = "errorNotification", Namespace = "http://def")]
public class ErrorNotification
{
[XmlAttribute(AttributeName = "vcs-pos", Namespace = "http://www.w3.org/2000/xmlns/")]
public string VcsPosNamespace { get; set; }
[XmlAttribute(AttributeName = "vcs-device", Namespace = "http://www.w3.org/2000/xmlns/")]
public string VcsDeviceNamespace { get; set; }
[XmlElement(ElementName = "errorText", Namespace = "")]
public string ErrorText { get; set; }
}
通过将带有[XmlAttribute]的字段添加到 ErrorNotification 类反序列化工作中。
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
var obj = Deserialize<ErrorNotification>(xml);