使用RestSharp对XML属性进行反序列化

时间:2016-04-27 15:32:20

标签: c# restsharp xml-deserialization

我有以下xml,我正在尝试反序列化它。我使用了RestSharp库,但是通过这个特殊的响应,我得到了一个空的资源列表。你知道库是否有XML中的自闭元素有问题吗?

<?xml version="1.0" encoding="utf-8"?>
<resourceList xmlns="..." xmlns:xsi="..." xsi:schemaLocation="..." location="...">
    <resourceURL location="../../../campaign/12" metaData1="12" metaData2="ACD Systems" metaData3="CPS" metaData4="Active" metaData5="Public" metaData6="No" metaData7="2005-10-28" metaData8="2020-12-31"/>
    <resourceURL location="../../../campaign/10607" metaData1="10607" metaData2="Aiseesoft" metaData3="CPS" metaData4="Active" metaData5="Public" metaData6="No" metaData7="2013-07-17" metaData8="2033-12-31"/>
    <resourceURL location="../../../campaign/567" metaData1="567" metaData2="AnchorFree Hotspot Shield Elite" metaData3="CPS" metaData4="Active" metaData5="Select" metaData6="No" metaData7="2011-10-03" metaData8="2031-12-31"/>
    <resourceURL location="../../../campaign/384" metaData1="384" metaData2="Avast" metaData3="CPS" metaData4="Active" metaData5="Select" metaData6="No" metaData7="2008-06-30" metaData8="2025-01-31"/>
</resourceList>

C#Classes:

[DeserializeAs(Name = "resourceList")]
public class ResourceList
{
    [DeserializeAs(Name = "resourceURL")]
    public List<ResourceUrl> ResourceURL { get; set; }
}

public class ResourceUrl
{
    public string Location { get; set; }

    public string MetaData1 { get; set; }

    public string MetaData2 { get; set; }
}

我最后的电话:

var response = _restClient.Execute<ResourceList>(request);

1 个答案:

答案 0 :(得分:0)

不,RestSharp对XML中的自闭元素没有任何问题。

当您使用默认的XML反序列化器(RestSharp.Deserializers.XmlDeserializer)时, 可以通过使用DeserializeAs属性推断出,你可以在中看到 library's source code他们在内部使用System.Xml中的XML解析器。

因此,您的XML示例应该反序列化而不会出现问题。但为此,我建议采用更简单,更快速的解决方案:

using System.Collections.Generic;
using RestSharp.Deserializers;

public class ResourceList : List<ResourceUrl> {}

[DeserializeAs(Name = "resourceURL")]
public class ResourceUrl {
    [DeserializeAs(Name = "location")]
    public string Location { get; set; }
    [DeserializeAs(Name = "metaData1")]
    public string MetaData1 { get; set; }
    [DeserializeAs(Name = "metaData2")]
    public string MetaData2 { get; set; }
}

//(...)

request.RootElement = null;
request.XmlNamespace = null;
var response = _restClient.Execute<ResourceList>(request);

但是,此解决方案不适用于当前的v105.2.3(仍在NuGet上的那个)。

您必须使用version of the class committed at the GitHub repository。只需获取该类的代码,将顶级命名空间语句更改为您自己的,保存到磁盘并将其添加到您的项目中。然后,只需将RestSharp客户端设置为使用反序列化器的新(更好)版本:

_restClient.AddHandler("application/xml",new XmlDeserializer());