转换XML字符串对象 [英] Convert XML String to Object

查看:141
本文介绍了转换XML字符串对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到XML字符串通过套接字,并希望这些转换为C#对象。

I am receiving XML strings over a socket, and would like to convert these to C# objects.

该消息的格式如下:

<msg>
   <id>1</id>
   <action>stop</action>
</msg>

我是新来的.Net,而我不知道执行此操作的最佳做​​法。我使用JAXB的Java面前,不知道是否有类似的东西,或者这是否会处理方式不同。

I am new to .Net, and am not sure the best practice for performing this. I've used JAXB for Java before, and wasn't sure if there is something similar, or if this would be handled a different way.

推荐答案

您需要使用它被安装在Windows SDK到一个目录东西 XSD.EXE 工具类似于:

You need to use the xsd.exe tool which gets installed with the Windows SDK into a directory something similar to:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

在64位计算机:

And on 64-bit computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin

和在Windows 10计算机:

And on Windows 10 computers:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

在第一次运行时,您可以使用 XSD.EXE 键,您将您的样品XML转换为XSD文件(XML架构文件):

On the first run, you use xsd.exe and you convert your sample XML into a XSD file (XML schema file):

xsd yourfile.xml

这为您提供了 yourfile.xsd ,它在第二个步骤中,您可以再次使用转换 XSD.EXE 成C#类:

This gives you yourfile.xsd, which in a second step, you can convert again using xsd.exe into a C# class:

xsd yourfile.xsd /c

这应该给你一个文件 yourfile.cs 其中将包含您可以使用反序列化你得到的XML文件C#类 - 是这样的:

This should give you a file yourfile.cs which will contain a C# class that you can use to deserialize the XML file you're getting - something like:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml"));

应工作pretty于大多数情况下。

Should work pretty well for most cases.

更新: XML序列化将采取任何流作为其输入 - 无论是一个文件或内存流将被罚款:

Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
msg resultingMessage = (msg)serializer.Deserialize(memStream);

或者用一个StringReader:

or use a StringReader:

XmlSerializer serializer = new XmlSerializer(typeof(msg));
StringReader rdr = new StringReader(inputString);
msg resultingMessage = (msg)serializer.Deserialize(rdr);

这篇关于转换XML字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆