I’m working on an integration with a third party application that sends us an XML message. Their XML looks something like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE theirObj SYSTEM "theirDTD-2.0.dtd">
<theirObj>
<properties>
<datasource>ThirdParty</datasource>
<datetime>2009-03-05T14:45:39</datetime>
</properties>
<data>
...
</data>
</theirObj>
I’m trying to deserialize it using the XmlSerializer:
public theirObj Deserialize(string message) {
if( string.IsNullOrWhiteSpace( message ) ) {
throw new ArgumentNullException( "message" );
}
XmlSerializer xmlSerializer = new XmlSerializer( typeof(theirObj ) );
TextReader textReader = new StringReader( message );
using (XmlReader xmlReader = new XmlTextReader( textReader )) {
object deserializedObject = xmlSerializer.Deserialize( xmlReader );
theirObj ent = deserializedObject as theirObj ;
if (ent == null) {
throw new InvalidCastException("Unable to cast deserialized object to an theirObj object. {0}".FormatInvariant( deserializedObject));
}
return ent;
}
}
}
I generated the objects using xsd.exe.
If I remove the <!DOCTYPE> tag then it deserializes fine.
Is there a way to get XmlSerializer to ignore the <!DOCTYPE> tag?
I know I could strip it out before passing it the XmlSerializer, but I’d rather not go to that level of XML manipulation if I don’t have to.
Instead of using
XmlTextReader, callXmlReader.Createand pass it anXmlReaderSettingsobject withDtdProcessingset toIgnore:Note: The
DtdProcessingproperty was added in .NET 4.0. In .NET 3.5, you can instead setProhibitDtdtofalseandXmlResolvertonull: