反序列化XML以使用自动生成的属性进行分类 [英] Deserialize XML to class with auto generated properties
问题描述
我有一个Windows服务,该服务将侦听通过HTTP发送到Windows服务的XML数据包.我想创建一个具有基于xml属性的类.让我们假设我收到了以下xml:
I have a Windows service that will be listening for XML packets being sent over HTTP to the windows service. I want to create a class with properties based on the xml. let us assume I received the following xml:
<persondetails>
<name>abc</name>
<surname>def</surname>
<age>22</age>
</persondetails>
我希望能够反序列化此xml以基于此信息创建新的类,或者只是反序列化此xml为可以访问属性的对象.
该类需要根据收到的每个xml创建,因为它们会有所不同,因此我无法创建一个类,而只能将其反序列化为typeof类.
我查看了xsd工具,但仅在命令提示符下找到了使用此工具的示例.我需要自动完成此操作,而无需任何用户交互.
i want to be able to deserialize this xml to create a new class based on this information, or just deserialize this xml into an object where I can access the attributes.
The class needs to be created according to every xml received, since they will differ, so I can''t create a class and just deserialize this to the typeof class.
I looked at xsd tool, but only found examples where working with this in the command prompt. I need it to be done automatically, without any user interaction.
推荐答案
我已经使用ExpandoObject在过去的项目中做到了这一点.
类似的东西:
I have used the ExpandoObject to do exactly this in a past project.
something like:
dynamic personDetails = new ExpandoObject();
var personLookup = (IDictionary<string, object>)personDetails;
personLookup["Name"] = yourXmlValue;
我在这里排除了XLinq,但是您应该了解要点.
然后,您可以传递动态对象,并像常规属性一样对其进行访问:
即
I''ve excluded the XLinq here, but you should get the gist.
You can then pass the dynamic object around and just access it like regular properties:
i.e.
var name = personDetails.Name;
这篇关于反序列化XML以使用自动生成的属性进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!