2

我在反序列化 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: 
4

2 回答 2

3

It will work if you create your serializer as below

var xSerializer = new XmlSerializer(typeof(bool),null, null, 
                         new XmlRootAttribute("boolean"), 
                         "http://schemas.microsoft.com/2003/10/serialization/");
于 2012-10-22T15:39:47.683 回答
0

You can't use xml namespaces and attributes if you want to deserialize a boolean. Infact you have to deserialize this:

string xml = "<boolean>false</boolean>";
于 2012-10-22T15:39:56.760 回答