Deserialize object property with StringReader vs XmlNodeReader

百般思念 提交于 2019-12-17 07:55:28

问题


Why does XmlSerializer populate my object property with an XmlNode array when deserializing an empty typed element using XmlNodeReader instead of an empty string like it does when using StringReader (or XmlTextReader)?

The second assertion in the following code sample fails:

var doc = new XmlDocument();
doc.Load(new StringReader(@"
    <Test xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
          xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
      <Value xsi:type=""xsd:string"" />
    </Test>"));
var ser = new XmlSerializer(typeof (Test));

var reader1 = new StringReader(doc.InnerXml);
var obj1 = (Test) ser.Deserialize(reader1);
Debug.Assert(obj1.Value is string);

var reader2 = new XmlNodeReader(doc.FirstChild);
var obj2 = (Test) ser.Deserialize(reader2);
Debug.Assert(obj2.Value is string);

public class Test
{
    public object Value { get; set; }
}

I'm guessing it has something to do with the null internal NamespaceManager property but I'm not sure how to work around this mysterious limitation. How can I reliably deserialize a subset of my parsed XML document without converting it back into a string and re-parsing?


回答1:


It looks like this is a very old XmlNodeReader bug that Microsoft have no intention of fixing. (Archived Microsoft Connect link here). I found a workaround on Lev Gimelfarb's blog here that adds namespaces to the reader's NameTable as prefixes are looked up.

public class ProperXmlNodeReader : XmlNodeReader
{
    public ProperXmlNodeReader(XmlNode node) : base(node)
    {
    }

    public override string LookupNamespace(string prefix)
    {
        return NameTable.Add(base.LookupNamespace(prefix));
    }
}


来源:https://stackoverflow.com/questions/30102275/deserialize-object-property-with-stringreader-vs-xmlnodereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!