我一直在努力让 RestSharp 解析以下返回的 XML 数据:
<?xml version="1.0" encoding="UTF-8"?>
<TICKETANYWHERE>
<COUPON VER="1.0">
<RESPONSE>
<TEMPLATELIST>
<TEMPLATE ID="000000001">
<NAME>Some name</NAME>
</TEMPLATE>
<TEMPLATE ID="000000001">
<NAME>Some other name</NAME>
</TEMPLATE>
</TEMPLATELIST>
</RESPONSE>
</COUPON>
</TICKETANYWHERE>
它是从 API 返回的,所以我无法更改此 XML。我创建了以下类来为 XML 文件建模:
public class Template
{
public string Id { get; set; }
public string Name { get; set; }
}
public class TemplateList : List<Template>
{}
public class Response
{
public TemplateList Templates { get; set; }
}
public class Coupon
{
public decimal Ver { get; set; }
public Response Response { get; set; }
}
public class TicketAnywhere
{
public Coupon Coupon { get; set; }
}
然后我创建了以下单元测试(灵感来自)
var d = new XmlDeserializer();
var response = new RestSharp.RestResponse();
var XML = "<TICKETANYWHERE><COUPON VER=\"1.0\"><RESPONSE><TEMPLATELIST><TEMPLATE ID=\"00000001\"><NAME>Some name</NAME></TEMPLATE></TEMPLATELIST></RESPONSE></COUPON></TICKETANYWHERE>";
response.Content = XML;
var r = d.Deserialize<TicketAnywhere>(response);
但是,r.Coupon 为 NULL。我在这里做错了什么?
更新:我试图通过将 XML 和测试更改为以下内容,将问题归结为最简单的形式:
public class Template
{
public string Id { get; set; }
public string Name { get; set; }
}
public class TemplateList
{
public List<Template> Templates { get; set; }
}
[Test]
public void AnotherTest()
{
var XML = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<TEMPLATELIST>
<TEMPLATE ID=""00000001"">
<NAME>Some name</NAME>
</TEMPLATE>
<TEMPLATE ID=""00000002"">
<NAME>Some name</NAME>
</TEMPLATE>
</TEMPLATELIST>";
var d = new XmlDeserializer();
var response = new RestSharp.RestResponse();
response.Content = XML;
var r = d.Deserialize<TemplateList>(response);
Assert.That(2, Is.EqualTo(r.Templates.Count));
}
这又失败了。但是,如果我从 Template => TEMPLATE 更改类名,这一切似乎都有效。