It is not that hard.
My task was to deserialize xml files of the same structure which can be with or without a default namespace declaration.
First I found this discussion with the XmlTextReader solution: NamespaceIgnorantXmlTextReader.
But MSDN recommends not to use XmlTextReader and use XmlReader instead.
So we need to do the same thing on the XmlReader.
XmlReader is an abstract class and we need to do a wrapper first. Here is a good article how to do it. And here is a ready XmlWrappingReader.
Then we need to extend it:
public class XmlExtendableReader : XmlWrappingReader
{
private bool _ignoreNamespace { get; set; }
public XmlExtendableReader(TextReader input, XmlReaderSettings settings, bool ignoreNamespace = false)
: base(XmlReader.Create(input, settings))
{
_ignoreNamespace = ignoreNamespace;
}
public override string NamespaceURI
{
get
{
return _ignoreNamespace ? String.Empty : base.NamespaceURI;
}
}
}
That's it. Now we can use it and control both XmlReaderSettings and a namespace treatment:
XmlReaderSettings settings = new XmlReaderSettings()
{
CheckCharacters = false,
ConformanceLevel = ConformanceLevel.Document,
DtdProcessing = DtdProcessing.Ignore,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
ValidationType = ValidationType.None
};
using (XmlExtendableReader xmlreader = new XmlExtendableReader(reader, settings, true))
_entities = ((Orders)_serializer.Deserialize(xmlreader)).Order;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…