简体   繁体   English

将XML响应字符串反序列化为C#类

[英]Deserialize XML Response String to C# Class

I know there has been a good amount of posts on this, though I find this topic of .NET very difficult to comprehend. 我知道关于这方面的文章很多,尽管我发现很难理解.NET的这一主题。 I have an XML string that looks like this: 我有一个看起来像这样的XML字符串:

<?xml version="1.0" encoding="UTF-8"?>
<result command="searchhotels" tID="1460064669000001" ip="99.51.186.120"  date="2016-04-07 21:31:16" version="2.0" elapsedTime="7.1676669120789">
    <currencyShort>USD</currencyShort>
    <hotels count="2">
        <hotel runno="0" preferred="no" cityname="DUBAI" order="3" hotelid="275975">
            <from>292.767
                <formatted>292.77</formatted>
            </from>
            <availability>available</availability>
        </hotel>
        <hotel runno="1" preferred="yes" cityname="DUBAI" order="3" hotelid="31084">
            <from>278.7142
                <formatted>278.71</formatted>
            </from>
            <availability>available</availability>
        </hotel>
    </hotels>
    <successful>TRUE</successful>
</result>

I want to map this to a class, based on the documentation and posts that I've read I have no idea how to do this or what the class should look like. 我想根据已阅读的文档和帖子将其映射到一个类,但我不知道该如何做或该类应该是什么样子。 Help? 救命? Here is what I have so far.... 这是我到目前为止所拥有的...

"response" is the xml string... turning string into class: “响应”是xml字符串...将字符串转换为类:

        XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
        using (StringReader reader = new StringReader(response))
        {

            TResponse deserialized = (TResponse)serializer.Deserialize(reader);
            return deserialized;
        }

I do not know what the class should look like, I've tried turning that response into a C# class using online tools but nothing seems to work. 我不知道该类的外观,我曾尝试使用在线工具将该响应转换为C#类,但似乎无济于事。 So what should the class for this response look like? 那么,此响应的类应该是什么样的? And how can I turn the string into this class? 以及如何将字符串转换为此类?

Take a look at xsd.exe - google it - it is a little utility that you can use to generate .net class structures based on xml (it will infer structure) or xsd files. 看一下xsd.exe-谷歌浏览器-它是一个小实用程序,可用于基于xml生成.net类结构(它将推断结构)或xsd文件。

With it you can generate a class that you can populate in your deserialization code. 有了它,您可以生成一个可以在反序列化代码中填充的类。

If you just need to generate classes to deserialize your XML, you can try this online tool, Xml2CSharp . 如果只需要生成用于反序列化XML的类,则可以尝试使用此在线工具Xml2CSharp That shortcut might work. 该快捷方式可能有效。

Otherwise you'll need to generate a schema from your XML and then generate classes from the schema. 否则,您将需要从XML生成模式,然后从该模式生成类。 This article describes the steps clearly. 本文清楚地描述了步骤。

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

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