我从具有 XML 序列的 API 获得了这个 xml feed。
<?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 进行反序列化的一些选项。理想情况下,我想要类似下面的东西,但它显然不起作用。
public class MyResponse
{
public List<Setting> Settings { get; set;}
}
public class Setting
{
public int Cmd { get; set; }
public int Status { get; set; }
}
谢谢
最佳答案
您可以使用DotNetXmlDeserializer
RestSharp 打造 Microsoft 的 XmlSerializer
进行实际的反序列化。使用 XML serialization attributes 定义您的 MyResponse
类,如下所示指定元素名称以及对 Cmd/Status
元素交替序列的特殊处理:
[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);
原型(prototype) fiddle .
关于c# - 使用 RestSharp 进行 Xml 序列反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883177/