如何覆盖XmlTextReader字符实体扩展?

时间:2012-02-22 19:51:47

标签: xml entity character expansion xmltextreader

使用.Net框架,我需要将XML实体文本作为原始字符串值(未展开的字符实体)读取,以用于比较/合并功能。据我所知,没有办法直接关闭角色实体扩展。

我尝试从XmlTextReader派生并挂钩Read()方法,它拦截读取,但Value属性是只读的,我看不到任何修改传入文本的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace blah {
    class XmlRawTextReader : XmlTextReader {
        public XmlRawTextReader(string fileName) : base(fileName) { }

        public override bool Read() {
            bool result = base.Read();
            if (result == true && base.HasValue && base.NodeType == XmlNodeType.Text) {
                string s = this.Value;
                //this.Value = @"new value";  // does not work - read-only
            }
            return result;
        }
    }
}

有没有人知道如何禁用字符实体扩展或在读取字符串时更新字符串?

有点卡在这里,所以提前感谢您的想法...

1 个答案:

答案 0 :(得分:0)

将它放在后面燃烧器上一段时间后,答案变得明显:

虽然您无法轻松覆盖Read()方法来更改读取值,但您可以挂钩属性访问器来执行相同的操作:

using System;
using System.Collections.Generic;
using System.Xml;

namespace blah {

    class XmlCustomTextReader : XmlTextReader {

        private Func<string, List<KeyValuePair<string, string>>, string> _updateFunc;

        public XmlCustomTextReader(string fileName, Func<string, List<KeyValuePair<string, string>>, string> updateFunc = null) : base(fileName) {
            _updateFunc = updateFunc;
        }

        //
        // intercept and override value access - 'un-mangle' strings that were rewritten by XMLTextReader
        public override string Value {
            get {
                string currentvalue = base.Value;

                // only text nodes
                if (NodeType != XmlNodeType.Text)
                    return currentvalue;

                string newValue = currentvalue;

                // if a conversion function was provided, use it to update the string
                if (_updateFunc != null)
                    newValue = _updateFunc(currentvalue, null);

                return newValue;
            }
        }
    }
}

通过以下方式使用:

        Func<string, List<KeyValuePair<string, string>>, string> updateFunc = UpdateString;
        XmlCustomTextReader reader = new XmlCustomTextReader(fileName, updateFunc);
        reader.XmlResolver = new XmlCustomResolver(XmlCustomResolver.ResolverType.useResource);
        XDocument targetDoc = XDocument.Load(reader);

我希望这有助于将来......