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

前端 未结 2 1237
忘了有多久
忘了有多久 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:08

    In my case, as part of a provider's api versioning strategy, I came accross the need of supporting different response namespaces while deserialising with XmlSerializer to the same C# class.

    The responses are basically the same, but the root namespace in the response is different depending on the credentials passed to the service.

    So, I have used XmlWrappingReader approach to rename the namespace returned by the service to the namespace that the C# classes have attached through the XmlTypeAttribute.

    But just one caveat: use string intering as I suspect the XmlSerializer is using Object.ReferenceEquals while reading from the XmlReader to match against the target namespace in the c# class.

    In my case, the replacementNs parameter was obtained from the type's XmlTypeAttribute through reflection and apparently was not the exact same object reference as the string internally used by the XmlSerializer.

    I almost lost my hair with this silly thing…

    public class ReplaceNsXmlReader : XmlWrappingReader
    {
        private readonly string replacementNs;
    
        public ReplaceNsXmlReader(XmlReader reader, string replacementNs)
            : base(reader)
        {
            //
            // NOTE: String.Intern is here needed for the XmlSerializer
            // that will be using this reader to deserialize correctly
            //
    
            this.replacementNs = String.Intern(replacementNs);
        }
    
        public override string NamespaceURI
        {
            get => replacementNs;
        }
    }
    

提交回复
热议问题