我有以下代码:
public class TestStreamReader : StreamReader
{
.
.
public override int Read([In, Out] char[] buffer, int index, int count)
{
char[] charBuffer = new char[buffer.Length];
int i = base.Read(charBuffer, index, count);
string s = new string(charBuffer);
s = s.CleanInvalidXmlChars();
Buffer.BlockCopy(s.ToCharArray(), index, buffer, index, count);
return i;
}
}
但如果我跟随电话:
XmlReaderSettings settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Ignore
};
using ( DataSet ds = new DataSet() ) {
using ( TestStreamReader stream = new TestStreamReader(fileName) ) {
using ( XmlReader tr = XmlReader.Create(stream, settings) ) {
ds.ReadXml(tr);
ImportDataSet(ds);
}
}
}
public static string CleanInvalidXmlChars(this string input)
{
if ( string.IsNullOrWhiteSpace(input) ) {
return input;
}
return input.Replace(" ", " ");
}
我得到一个例外:
'说明'第53行的开始标记位置6与“描述”的结束标记不匹配。第53行,位置156.位于System.Xml.Xml.XmlTextRemplImpl.ParseElementContent()的System.Xml.XmlTextReaderImpl.ParseEndElement()的System.Xml.Xml.XmlTextReaderImpl.ThrowTagMismatch(NodeData startTag)的System.Xml.XmlTextReaderImpl.Throw(Exception e)
异常的原因是Read在开始时只被调用一次,而从未加载到下一个数据块。
有人可以解释为什么会这样吗?
答案 0 :(得分:0)
Buffer.BlockCopy适用于 BYTES ,因此如果使用字符复制数组,字节数需要乘以2或sizeof(char)
我要感谢Damien_The_Unbeliever的正确提示:
最终代码:
public override int Read([In, Out] char[] buffer, int index, int count)
{
char[] charBuffer = new char[buffer.Length];
int i = base.Read(charBuffer, index, count);
string s = new string(charBuffer);
s = s.CleanInvalidXmlChars();
char[] tempBuffer = s.ToCharArray();
int sizeOfChar = sizeof(char);
Buffer.BlockCopy(tempBuffer, index*sizeOfChar, buffer, index*sizeOfChar, count*sizeOfChar);
return i;
}