我正在为我的WEB API定义新的合同,我想要具有特定的XML格式,以便它可以接受下面的XML,我想将其解析为下面的类类。 JSON格式完全按照我的预期映射,但XML不是。
如何停止在XML中生成“成员”包装器节点?
我想要解析成类的XML:
<MembersUpdate>
<NotificationUrl>http://yoururl/member/profile/</NotificationUrl>
<Timestamp >2017-04-11T12:13:35.6516915Z</Timestamp>
<Member>
<MemberId>0</MemberId>
<LastUpdated>0001-01-01T00:00:00</LastUpdated>
</Member>
<Member>
<MemberId>0</MemberId>
<LastUpdated>0001-01-01T00:00:00</LastUpdated>
</Member>
<Member>
<MemberId>0</MemberId>
<LastUpdated>0001-01-01T00:00:00</LastUpdated>
</Member>
<Member>
<MemberId>0</MemberId>
<LastUpdated>0001-01-01T00:00:00</LastUpdated>
</Member>
</MembersUpdate>
映射类:
/// <remarks/>
[DataContract]
public partial class MembersUpdate
{
/// <remarks/>
[DataMember]
public string NotificationUrl { get; set; }
/// <remarks/>
[DataMember]
public System.DateTime Timestamp { get; set; }
/// <remarks/>
[DataMember]
public MembersUpdateMember[] Member { get; set; }
}
/// <remarks/>
[DataContract]
public partial class MembersUpdateMember
{
/// <remarks/>
[DataMember]
public byte MemberId { get; set; }
/// <remarks/>
[DataMember]
public System.DateTime LastUpdated { get; set; }
}
但是,渲染的示例确实有其他节点,并且无法解析原始XML。我添加了为以下结构渲染的样本:
<MembersUpdate xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/CivicaSystemsLtd.Areas.Notices.ApiControllers">
<Member>
<MembersUpdateMember>
<LastUpdated>2017-04-11T23:58:06.6310087+01:00</LastUpdated>
<MemberId>64</MemberId>
</MembersUpdateMember>
<MembersUpdateMember>
<LastUpdated>2017-04-11T23:58:06.6310087+01:00</LastUpdated>
<MemberId>64</MemberId>
</MembersUpdateMember>
</Member>
<NotificationUrl>sample string 1</NotificationUrl>
<Timestamp>2017-04-11T23:58:06.6300095+01:00</Timestamp>
</MembersUpdate>
答案 0 :(得分:0)
这几乎是不可能的,因为WebAPI使用DataContractSerializer
。
如果您可以切换到XmlSerializer
,则可以执行以下操作:
[XmlElement(ElementName = "Member")]
public MembersUpdateMember[] Member { get; set; }
您可以通过attribute on your Controller开启需求:
public class UseXmlSerializerAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings,
HttpControllerDescriptor controllerDescriptor)
{
var xmlFormater = new XmlMediaTypeFormatter {UseXmlSerializer = true};
controllerSettings.Formatters.Clear();
controllerSettings.Formatters.Add(xmlFormater);
}
}
然后在你的控制器上使用它:
[UseXmlSerializer]
public class FooController : ApiController
{
}