How do I create a XmlTextReader that ignores Namespaces and does not check characters

前端 未结 2 1251
忘了有多久
忘了有多久 2020-12-21 12:07

I want to use a XmlTextReader that ignores Namespaces and does not check characters. To ignore namespaces I can set the property Namespaces=false a

2条回答
  •  暖寄归人
    2020-12-21 12:30

    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;
    

提交回复
热议问题