【发布时间】:2011-01-16 20:34:13
【问题描述】:
有没有办法异步访问 XmlReader? xml 是从许多不同的客户端(如 XMPP)从网络中传入的;它是<action>...</action> 标签的恒定流。
我追求的是能够使用类似 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;
};
【问题讨论】:
-
您的计数器在这种情况下失败,这是完全合法的 XML:
,其中读取边界在 baz 之前。