阅读从XML网络数据流全要素数据流、要素、网络、XML

2023-09-03 17:12:37 作者:丶花少

我写在C#.NET 4.0的网络服务器。有超过我能接受完整的XML内容的网络TCP / IP连接。他们定期到,我需要马上处理。每个XML元素本身就是一个完整的XML文档,所以它有一个开口元件,若干子节点和一个闭合元件。有对于整个流没有单一根元素。所以,当我打开连接,我得到的是这样的:

I am writing a network server in C# .NET 4.0. There is a network TCP/IP connection over which I can receive complete XML elements. They arrive regularly and I need to process them immediately. Each XML element is a complete XML document in itself, so it has an opening element, several sub-nodes and a closing element. There is no single root element for the entire stream. So when I open the connection, what I get is like this:

<status>
    <x>123</x>
    <y>456</y>
</status>

然后一段时间后继续:

Then some time later it continues:

<status>
    <x>234</x>
    <y>567</y>
</status>

等。我需要一种方法来阅读完整的XML字符串,直到状态元素就完成了。我不想做纯文本的阅读方法,因为我不知道在什么格式的数据到达。我绝不能等到整个流完成时,如通常在别处所述。我已经使用XmlReader类尝试,但它的文档是怪异,该方法不奏效,第一个元素被丢失,发送第二个元素后,出现XmlException因为有两个根本要素。

And so on. I need a way to read the complete XML string until a status element is complete. I don't want to do that with plain text reading methods because I don't know in what formatting the data arrives. I can in no way wait until the entire stream is finished, as is often described elsewhere. I have tried using the XmlReader class but its documentation is weird, the methods don't work out, the first element is lost and after sending the second element, an XmlException occurs because there are two root elements.

推荐答案

试试这个:

var settings = new XmlReaderSettings
{
    ConformanceLevel = ConformanceLevel.Fragment
};

using (var reader = XmlReader.Create(stream, settings))
{
    while (!reader.EOF)
    {
        reader.MoveToContent();

        var doc = XDocument.Load(reader.ReadSubtree());

        Console.WriteLine("X={0}, Y={1}",
            (int)doc.Root.Element("x"),
            (int)doc.Root.Element("y"));

        reader.ReadEndElement();
    }
}