将 XML 字符串转换为对象
我正在通过套接字接收 XML 字符串,并希望将它们转换为 C# 对象。
消息的形式如下:
<msg>
<id>1</id>
<action>stop</action>
</msg>
这怎么办?
I am receiving XML strings over a socket, and would like to convert these to C# objects.
The messages are of the form:
<msg>
<id>1</id>
<action>stop</action>
</msg>
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
您需要使用
xsd.exe
工具,该工具与 Windows SDK 一起安装到类似于以下内容的目录中:在 64 位计算机上:
在 Windows 10 计算机上:
在第一次运行时,您使用
xsd.exe
并将示例 XML 转换为 XSD 文件(XML 架构文件):这将为您提供
yourfile.xsd
,在第二步中,您可以再次转换该文件在 C# 类中使用xsd.exe
:这应该会为您提供一个文件
yourfile.cs
,其中包含一个 C# 类,您可以使用该类来反序列化您所创建的 XML 文件得到 - 类似于:在大多数情况下应该工作得很好。
更新: XML 序列化程序将采用任何流作为其输入 - 文件或内存流都可以:
或者使用 StringReader:
You need to use the
xsd.exe
tool which gets installed with the Windows SDK into a directory something similar to:And on 64-bit computers:
And on Windows 10 computers:
On the first run, you use
xsd.exe
and you convert your sample XML into a XSD file (XML schema file):This gives you
yourfile.xsd
, which in a second step, you can convert again usingxsd.exe
into a C# class: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:Should work pretty well for most cases.
Update: the XML serializer will take any stream as its input - either a file or a memory stream will be fine:
or use a StringReader:
你有两种可能性。
方法1.XSD工具
Suppose that you have your XML file in this location
C:\path\to\xml\file.xml
您可以在
开始菜单>中找到它节目>微软 Visual Studio 2012 > Visual Studio 工具
或者,如果您使用的是 Windows 8,只需在“开始”屏幕中输入“开发人员命令提示符”,即可
cd /D "C:\path 将位置更改为 XML 文件目录\to\xml"
xsd file.xml
从 xml 文件创建 XSD 文件创建 C# 类 >xsd /c file.xsd
就是这样!您已从
C:\path\to\xml\file.cs
中的 xml 文件生成了 C# 类方法 2 - 粘贴特殊
Required Visual Studio 2012+ with .Net Framework >= 4.5 as project target and 'Windows Communication Foundation' individual component installed
Edit >粘贴特殊>将 XML 粘贴为类
就是这样!
使用
这个辅助类的用法非常简单:
您现在所要做的就是:
You have two possibilities.
Method 1. XSD tool
Suppose that you have your XML file in this location
C:\path\to\xml\file.xml
You can find it in
Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools
Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
cd /D "C:\path\to\xml"
xsd file.xml
xsd /c file.xsd
And that's it! You have generated C# classes from xml file in
C:\path\to\xml\file.cs
Method 2 - Paste special
Required Visual Studio 2012+ with .Net Framework >= 4.5 as project target and 'Windows Communication Foundation' individual component installed
Edit > Paste special > Paste XML As Classes
And that's it!
Usage
Usage is very simple with this helper class:
All you have to do now, is:
尝试使用此方法将 Xml 转换为对象。它正是为您正在做的事情而设计的:
使用以下代码调用它:
Try this method to Convert Xml to an object. It is made for exactly what you are doing:
Call it using this code:
只需以管理员身份运行 Visual Studio 2013 ...
复制 Xml 文件的内容。
转到 Visual Studio 2013 >编辑>选择性粘贴>将 Xml 粘贴为 C# 类
它将根据您的 Xml 文件内容创建您的 C# 类。
Simply Run Your Visual Studio 2013 as Administration ...
Copy the content of your Xml file..
Go to Visual Studio 2013 > Edit > Paste Special > Paste Xml as C# Classes
It will create your c# classes according to your Xml file content.
以防万一有人可能会发现这很有用:
您可以使用以下方式调用它:
Just in case anyone might find this useful:
You can call it using:
您可以按照上面的描述生成类,或者手动编写它们:
然后您可以使用 ExtendedXmlSerializer 进行序列化和反序列化。
安装
您可以从 nuget 安装 ExtendedXmlSerializer 或运行以下命令:
序列化:
反序列化
此序列化器支持:
ExtendedXmlSerializer 支持 .NET 4.5 或更高版本和.NET Core。您可以将其与 WebApi 和 AspCore 集成。
You can generate class as described above, or write them manually:
Then you can use ExtendedXmlSerializer to serialize and deserialize.
Instalation
You can install ExtendedXmlSerializer from nuget or run the following command:
Serialization:
Deserialization
This serializer support:
ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.
您可以使用 xsd.exe 在 .Net 中创建架构绑定类,然后使用 XmlSerializer 反序列化字符串:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx
You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx
简化达米安的精彩答案,
Simplifying Damian's great answer,
我已经浏览了截至目前(2020-07-24)的所有答案,并且必须有一种更简单更熟悉的方法来解决这个问题,如下所示。
两种情况... 一种情况是 XML 字符串格式良好,即它以
)之前,输入“utf-16”?> 或其类似内容。另一种是如果它格式不正确,即只有根元素(例如问题中的
)及其子节点。首先,只是一个简单的类,其中包含与 XML 中根节点的子节点(不区分大小写的名称)相匹配的属性。所以,从问题来看,它会是这样的......
以下是代码的其余部分......
I have gone through all the answers as at this date (2020-07-24), and there has to be a simpler more familiar way to solve this problem, which is the following.
Two scenarios... One is if the XML string is well-formed, i.e. it begins with something like
<?xml version="1.0" encoding="utf-16"?>
or its likes, before encountering the root element, which is<msg>
in the question. The other is if it is NOT well-formed, i.e. just the root element (e.g.<msg>
in the question) and its child nodes only.Firstly, just a simple class that contains the properties that match, in case-insensitive names, the child nodes of the root node in the XML. So, from the question, it would be something like...
The following is the rest of the code...
我知道这个问题很老了,但是我偶然发现了它,并且我有一个与其他人不同的答案:-)
通常的方法(正如上面的评论者提到的)是生成一个类并反序列化你的xml。
但是(警告:这里无耻的自我推销)我刚刚发布了一个 nuget 包,这里,您不必这样做。你只需走:
就是这样,不需要其他任何东西。而且,最重要的是,如果您的 xml 发生更改,您的对象也会自动更改。
如果您希望直接下载 dll,则 github 页面位于此处。
I know this question is old, but I stumbled into it and I have a different answer than, well, everyone else :-)
The usual way (as the commenters above mention) is to generate a class and de-serialize your xml.
But (warning: shameless self-promotion here) I just published a nuget package, here, with which you don't have to. You just go:
That is literally it, nothing else needed. And, most importantly, if your xml changes, your object changes automagically as well.
If you prefer to download the dll directly, the github page is here.
使用以下方法使用 JAXB 将 XML 字符串转换为 DTO
Use below method to convert XML String to DTO using JAXB
如果您有 xml 消息的 xsd,则可以使用 .Net xsd.exe 工具生成 C# 类。
然后可以使用该 .Net 类生成 xml。
If you have the xsd of the xml message then you can generate c# classes using the .Net xsd.exe tool.
This .Net classes can then be used to generate the xml.
除了此处的其他答案之外,您自然可以使用 XmlDocument< /a> 类,用于类似 XML DOM 的读取,或 XmlReader,仅快进阅读器,“手动”完成。
In addition to the other answers here you can naturally use the XmlDocument class, for XML DOM-like reading, or the XmlReader, fast forward-only reader, to do it "by hand".
另一种使用高级 xsd 到 c# 类生成工具的方法:xsd2code.com。这个工具非常方便且功能强大。它比 Visual Studio 中的 xsd.exe 工具具有更多的自定义功能。 Xsd2Code++ 可以自定义为使用列表或数组,并支持具有大量 Import 语句的大型模式。
注意一些功能,
或 Visual Basic 代码。
[RangeAttribute=true/false])。
Another way with an Advanced xsd to c# classes generation Tools : xsd2code.com. This tool is very handy and powerfull. It has a lot more customisation than the xsd.exe tool from Visual Studio. Xsd2Code++ can be customised to use Lists or Arrays and supports large schemas with a lot of Import statements.
Note of some features,
or Visual Basic code.
[RangeAttribute=true/false]).