简体   繁体   English

解析来自TCP / IP连接的XML字符串

[英]Parsing XML string coming from a TCP/IP connection

I need to parse standard XML structures coming from a TCP/IP connection. 我需要解析来自TCP / IP连接的标准XML结构。 The data is kept as a string variable. 数据保存为字符串变量。 This means that in any given time the data in my hand can be incomplete (an incomplete XML structure), or a complete XML structure with incomplete leftover (the beginning of the next XML structure). 这意味着在任何给定时间内,我手中的数据可能是不完整的(不完整的XML结构),或者是一个具有不完整剩余的完整XML结构(下一个XML结构的开头)。

Most of the structures are not 'empty': 大多数结构都不是“空的”:

<Message>
  <Param1 value = "val1"/>
  <Param2 value = "val2"/>
</Message>

But there are also 'empty' ones: 但也有“空”的:

<Message status="ack" />

So just searching for </Message> and making a split there is not good enough. 所以只搜索</Message>并进行拆分就不够了。

How can I part the complete structure from the next partial structure? 如何从下一个部分结构中分离出完整的结构? Is there a cleaner solution other than creating my own state-machine for this and checking byte by byte? 除了为此创建自己的状态机并逐字节检查之外,是否有更清晰的解决方案?

You can use a dictionary for each message 您可以为每条消息使用字典

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<Message>" +
                  "<Param1 value = \"val1\"/>" +
                  "<Param2 value = \"val2\"/>" +
                "</Message>" +
                "<Message>" +
                  "<Param1 value = \"val1\"/>" +
                  "<Param2 value = \"val2\"/>" +
                "</Message>";


            XElement message = 
                new XElement("Root", input);

            var results = message.Elements("Message")
                .Where(x => x.HasElements)
                .Select(x => x.Elements()
                    .GroupBy(y => y.Name.LocalName, z => z)
                    .ToDictionary(y => y.Key, z => (string)z.FirstOrDefault()
                        .Attribute("value")))
                .ToList();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM