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

查看:61
本文介绍了将 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 的新手,不确定执行此操作的最佳实践.我之前在 Java 中使用过 JAXB,但不确定是否有类似的东西,或者是否会以不同的方式处理.

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.

推荐答案

您需要使用 xsd.exe 工具,该工具随 Windows SDK 一起安装到类似于以下内容的目录中:

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

C:Program FilesMicrosoft SDKsWindowsv6.0Ain

在 64 位计算机上:

And on 64-bit computers:

C:Program Files (x86)Microsoft SDKsWindowsv6.0Ain

在 Windows 10 计算机上:

And on Windows 10 computers:

C:Program Files (x86)Microsoft SDKsWindowsv7.0Ain

在第一次运行时,您使用 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,其中将包含一个 C# 类,你可以用它来反序列化你得到的 XML 文件 - 类似于:

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"));

在大多数情况下应该可以很好地工作.

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天全站免登陆