.NET Framework - Deserializing with xsi:type="xsd:string"

Asked By Jon Davis on 13-Sep-09 08:34 AM
I have a custom hashtable (a Dictionary<string, object>) for type-varying
(database-derived) values with which I have implemented IXmlSerializable using
XmlSerializer. The output of the value of a string typed as System.Object is
like so:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">it works</anyType>

When I use more or less the same XmlSerializer to deserialize this value, I
get an error:

System.InvalidOperationException: Namespace prefix 'xsd' is not defined.

I see what is going on, but what do I need to do from here?

Thanks for any help,
Jon Davis

Martin Honnen replied on 13-Sep-09 08:43 AM
There should be a namespace declaration
Usually the XmlSerializer writes that out together with the xmlns:xsi
namespace declaration.


Martin Honnen --- MVP XML
Jon Davis replied on 13-Sep-09 06:32 PM
Well there is not and it does not.

// TValue type is currently string, value is "it works"
var valueSerializer = new XmlSerializer(typeof (TValue));
valueSerializer.Serialize(writer, value);
// this outputs to the writer stream:
// <anyType xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">it works</anyType>

Jon Davis replied on 13-Sep-09 07:21 PM
Must be something w/ that XmlWriter, I cannot repro with the simplest
scenario using just a MemoryStream.

The context of serialization and deserialization and the writer / reader I am
using is IXmlSerializable's Serialize / Deserialize methods. I do not have
control over the root element in this context.


Jon Davis replied on 13-Sep-09 08:16 PM
Sorry, TValue was typeof(object), not typeof(string). Changes a lot, no

I have taken the reader/writer out of context and decided to do this in an
isolated reader/writer, then inject the XML back into the original
reader/writer. This gave me the xmlns:xsd=".../XMLSchema" declaration. But
then I got new errors about unexpected namespace declarations (in a child
XML node). So now I am trying to strip that out using XmlDocument. This is
getting messy.