0

.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;
        }
    }
}

文字エンティティの展開を無効にする方法、または読み取った時点で文字列を更新する方法を知っている人はいますか?

ちょっとここで立ち往生しているので、事前にアイデアをありがとう...

4

1 に答える 1

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);

これが将来誰かに役立つことを願っています...

于 2012-03-01T19:21:35.317 に答える