有没有一种方法可以异步访问XmlReader?XML是从许多不同的客户端,例如XMPP中通过网络传输的;它是一个不断流动的...标签序列。
我希望能够使用类似于BeginRead / EndRead的接口。我设想的最佳解决方案是在底层网络流上对0字节进行异步读取,然后当某些数据到达时,调用XmlReader上的Read - 这将会阻塞直到节点的所有数据都可用。该解决方案大致如下:
我希望能够使用类似于BeginRead / EndRead的接口。我设想的最佳解决方案是在底层网络流上对0字节进行异步读取,然后当某些数据到达时,调用XmlReader上的Read - 这将会阻塞直到节点的所有数据都可用。该解决方案大致如下:
private Stream syncstream;
private NetworkStream ns;
private XmlReader reader;
//this code runs first
public void Init()
{
syncstream = Stream.Synchronized(ns);
reader = XmlReader.Create(syncstream);
byte[] x = new byte[1];
syncstream.BeginRead(x, 0, 0, new AsynchronousCallback(ReadCallback), null);
}
private void ReadCallback(IAsyncResult ar)
{
syncstream.EndRead(ar);
reader.Read(); //this will block for a while, until the entire node is available
//do soemthing to the xml node
byte[] x = new byte[1];
syncstream.BeginRead(x, 0, 0, new AsynchronousCallback(ReadCallback), null);
}
编辑:这是一个可能的算法,用于判断一个字符串是否包含完整的XML节点?
Func<string, bool> nodeChecker = currentBuffer =>
{
//if there is nothing, definetly no tag
if (currentBuffer == "") return false;
//if we have <![CDATA[ and not ]]>, hold on, else pass it on
if (currentBuffer.Contains("<![CDATA[") && !currentBuffer.Contains("]]>")) return false;
if (currentBuffer.Contains("<![CDATA[") && currentBuffer.Contains("]]>")) return true;
//these tag-related things will also catch <? ?> processing instructions
//if there is a < but no >, we still have an open tag
if (currentBuffer.Contains("<") && !currentBuffer.Contains(">")) return false;
//if there is a <...>, we have a complete element.
//>...< will never happen because we will pass it on to the parser when we get to >
if (currentBuffer.Contains("<") && currentBuffer.Contains(">")) return true;
//if there is no < >, we have a complete text node
if (!currentBuffer.Contains("<") && !currentBuffer.Contains(">")) return true;
//> and no < will never happen, we will pass it on to the parser when we get to >
//by default, don't block
return false;
};