我遇到了对XML元素进行反序列化的问题,我假设它与反序列化器找不到的XML元素中的名称空间有关。
数据来自外部源,我无法将其修改为字符串,而且我使用的是C#4.0。
任何帮助,非常感谢。
string xml = "<boolean xmlns=\"http://schemas.microsoft.com/2003/10/serialization/\">false</boolean>";
var xSerializer = new XmlSerializer(typeof(bool));
using (var sr = new StringReader(xml))
using (var xr = XmlReader.Create(sr))
{
var y = xSerializer.Deserialize(xr);
}
错误:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=There is an error in XML document (1, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
...
...
...
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=<boolean xmlns='http://schemas.microsoft.com/2003/10/serialization/'> was not expected.
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializationPrimitiveReader.Read_boolean()
at System.Xml.Serialization.XmlSerializer.DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
InnerException:
答案 0 :(得分:3)
如果您按照以下方式创建序列化程序,它将起作用
var xSerializer = new XmlSerializer(typeof(bool),null, null,
new XmlRootAttribute("boolean"),
"http://schemas.microsoft.com/2003/10/serialization/");
答案 1 :(得分:0)
如果要反序列化布尔值,则不能使用xml命名空间和属性。事实上,你必须反序列化:
string xml = "<boolean>false</boolean>";