gpt4 book ai didi

c# - .NET 中的异步 XmlReader?

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:36 24 4
gpt4 key购买 nike

有没有办法异步访问 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;
};

最佳答案

XmlReader 以 4kB block 的形式缓冲,如果我记得几年前我看过这个的话。您可以将入站数据填充到 4kB(恶心!),或者使用更好的解析器。我通过将 James Clark 的 XP (Java) 作为 Jabber-Net 的一部分移植到 C# 来修复此问题,此处:

http://code.google.com/p/jabber-net/source/browse/#svn/trunk/xpnet

它是 LGPL,只处理 UTF8,没有打包使用,几乎没有文档,所以我不推荐使用它。 :)

关于c# - .NET 中的异步 XmlReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2263852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com