ASP.NET WebAPI XML反序列化? [英] Asp.net WebAPI XML deserialize?
问题描述
我可以在发布请求后成功在我的ASP.net Web API项目中反序列化XML,
I can de-serialize the XML in my ASP.net Web API project in post request successfully,
XML:
<Request xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/TestAPI.Models">
<Child>
<CountryISO>
<country xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d4p1:string>CA</d4p1:string>
<d4p1:string>US</d4p1:string>
</country>
</CountryISO>
</Child>
</Request>
模型
namespace TestWebTuiAPI.Models
{
public class Request
{
public Trip Child{ get; set; }
}
public class Child
{
public CountryISO CountryISO { get; set; }
}
public class CountryISO
{
[XmlElement("country")]
public List<string> country { get; set; }
}
}
现在,我需要执行上述所有步骤,才能使我的Post Request在ASP .Net Web API中运行.如果我从模型中删除[XmlElement("country")]属性,则XML中的CountryISO标签将返回null或空值.
Now,I need do all the above steps to make my Post Request working in the ASP .Net Web API. If I remove the [XmlElement("country")] attribute from the model, the CountryISO tag in the XML returns null or empty value.
我想在这里实现的是使用POST请求成功地反序列化以下XML,
what I want to achieve here is to de-serialize the following XML successfully using POST request,
XML:
<Request>
<Child>
<CountryISO>
<country>CA</country>
<country>US</country>
</CountryISO>
</Child>
</Request>
如果我尝试将其发布到上述XML之上,则会收到无效请求,并且会收到一个空模型.我需要在第一个XML中添加标头(父节点和CountryISO节点),以使其成功工作.我尝试了各种解决方案,但徒劳无功.
If I try to post this above XML, I'm getting an invalid request and I'm receiving a null model. I need to add the headers(parent node and CountryISO node) in the first XML to make it work successfully. I've tried various solutions but in vain.
任何建议将不胜感激.
如果我使用
config.Formatters.XmlFormatter.UseXmlSerializer = true;
我不需要标题,但是我在CountryISO标记内得到的是空值?
I don't need the headers but I'm getting empty values inside the CountryISO tag ?
推荐答案
如果您要像这样发布xml:
If you want to post xml like this:
<Request>
<Child>
<CountryISO>
<country>CA</country>
<country>US</country>
</CountryISO>
</Child>
</Request>
像上一个答案一样注释您的属性/类,但还要将 [XmlElement]
属性添加到country属性:
Annotate your properties/classes like the previous answer said, but also add the [XmlElement]
attribute to the country property:
[DataContract]
public class Request
{
[DataMember]
public Child Child { get; set; }
}
[DataContract]
public class Child
{
[DataMember]
public CountryISO CountryISO { get; set; }
}
[DataContract]
public class CountryISO
{
[DataMember]
[XmlElement("country")]
public List<string> country { get; set; }
}
这篇关于ASP.NET WebAPI XML反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!