您的1024字節緩衝區是來自System.IO.Stream的標準具體實現之一嗎?如果T是這樣,你可以創建你的XmlTextReader基本流周圍:
XmlTextReader tr = XmlTextReader.Create(myStreamInstance) ;
如果不是 - 比方說,比如,你從某種API的「讀書」的緩衝區 - 你需要實現自己的具體流,沿着這些線路(你應該需要做的是割肉出局的ReadNextFrame()方法,並可能實現你的構造函數)的東西:
public class MyStream : System.IO.Stream
{
public override bool CanRead { get { return true ; } }
public override bool CanSeek { get { return false ; } }
public override bool CanWrite { get { return false ; } }
public override long Length { get { throw new NotImplementedException(); } }
public override long Position {
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public override int Read(byte[] buffer , int offset , int count)
{
int bytesRead = 0 ;
if (!initialized)
{
Initialize() ;
}
for (int bytesRemaining = count ; !atEOF && bytesRemaining > 0 ;)
{
int frameRemaining = frameLength - frameOffset ;
int chunkSize = (bytesRemaining > frameRemaining ? frameRemaining : bytesRemaining) ;
Array.Copy(frame , offset , frame , frameOffset , chunkSize) ;
bytesRemaining -= chunkSize ;
offset += chunkSize ;
bytesRead += chunkSize ;
// read next frame if necessary
if (frameOffset >= frameLength)
{
ReadNextFrame() ;
}
}
return bytesRead ;
}
public override long Seek(long offset , System.IO.SeekOrigin origin) { throw new NotImplementedException(); }
public override void SetLength(long value) { throw new NotImplementedException(); }
public override void Write(byte[] buffer , int offset , int count) { throw new NotImplementedException(); }
public override void Flush() { throw new NotImplementedException(); }
private byte[] frame = null ;
private int frameLength = 0 ;
private int frameOffset = 0 ;
private bool atEOF = false ;
private bool initialized = false ;
private void Initialize()
{
if (initialized) throw new InvalidOperationException() ;
frame = new byte[1024] ;
frameLength = 0 ;
frameOffset = 0 ;
atEOF = false ;
initialized = true ;
ReadNextFrame() ;
return ;
}
private void ReadNextFrame()
{
//TODO: read the next (or first 1024-byte buffer
//TODO: set the frame length to the number of bytes actually returned (might be less than 1024 on the last read, right?
//TODO: set the frame offset to 0
//TODO: set the atEOF flag if we've exhausted the data source ;
return ;
}
}
然後實例如上您的XmlReader:
System.IO.Stream s = new MyStream() ;
System.Xml.XmlReader xr = XmlTextReader.Create(s) ;
乾杯!
XmlTextReader應該是解決方案,只需讓它管理緩衝區而不是手動執行。 – porges 2011-01-20 23:54:52