使用RestSharp的XML序列反序列化 [英] Xml Sequence deserialization with RestSharp

查看:66
本文介绍了使用RestSharp的XML序列反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个具有XML序列的API获取此xml feed.

I have this xml feed from an API with a XML sequence.

<?xml version="1.0" encoding="UTF-8" ?>
<Function>
    <Cmd>2002</Cmd>
    <Status>1</Status>
    <Cmd>2003</Cmd>
    <Status>0</Status>
    <Cmd>2004</Cmd>
    <Status>0</Status>
    <Cmd>1012</Cmd>
    <Status>3</Status>
    <Cmd>2006</Cmd>
    <Status>0</Status>
    <Cmd>2007</Cmd>
    <Status>0</Status>
    ...
</Function>

我已经尝试过使用Restsharp进行反序列化的一些选项.理想情况下,我希望拥有类似以下内容,但显然不起作用.

I already tried a few options for deserialization with Restsharp. Ideally I would like to have something like the following, but it's obviously not working.

public class MyResponse
{
    public List<Setting> Settings { get; set;}
}

public class Setting
{
    public int Cmd { get; set; }
    public int Status { get; set; }
}

谢谢

推荐答案

您可以使用 DotNetXmlDeserializer 以使Microsoft的

You can use the DotNetXmlDeserializer of RestSharp to make Microsoft's XmlSerializer do the actual deserialization. Define your MyResponse class as follows, using XML serialization attributes to specify element names and also special handling for the Cmd/Status alternating sequence of elements:

[XmlRoot("Function")]
public class MyResponse
{
    [XmlIgnore]
    public List<Setting> Settings { get; set; }

    /// <summary>
    /// Proxy property to convert Settings to an alternating sequence of Cmd / Status elements.
    /// </summary>
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    [XmlAnyElement]
    public XElement[] Elements 
    {
        get
        {
            if (Settings == null)
                return null;
            return Settings.SelectMany(s => new[] { new XElement("Cmd", s.Cmd), new XElement("Status", s.Status) }).ToArray();
        }
        set
        {
            if (value == null)
                Settings = null;
            else
                Settings = value.Where(e => e.Name == "Cmd").Zip(value.Where(e => e.Name == "Status"), (cmd, status) => new Setting { Cmd = (int)cmd, Status = (int)status }).ToList();
        }
    }
}

然后反序列化如下:

        var serializer = new DotNetXmlDeserializer();
        var myResponse = serializer.Deserialize<MyResponse>(response);

原型小提琴.

这篇关于使用RestSharp的XML序列反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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