我有一个商家帐户余额请求类,如下所示:
[Serializable]
[XmlRoot(ElementName = "accountbalance", Namespace = "", IsNullable = false)]
public class MerchantAccountBalanceRequest
{
[XmlElementAttribute("agent")]
public string Agent { get; set; }
[XmlElementAttribute("agentPin")]
public string AgentPin { get; set; }
}
这将产生以下XML:
<accountbalance>
<agent>aaaaaa</agent>
<agentPin>mmmmmm</agentPin>
</accountbalance>
我可以以某种方式在我的类上放置一个属性,以便对于MerchantAccountBalanceRequest
对象,我将得到以下XML:
<Envelope>
<Body>
<accountbalance>
<agent>aaaaaa</agent>
<agentPin>mmmmmm</agentPin>
</accountbalance>
</Body>
</Envelope>
也就是说,只需使用Envelope
和Body
元素进行包装。
答案 0 :(得分:1)
虽然您无法通过请求类的属性实现此目的,但您可以将请求包含在代表Envelope
和Body
元素的其他类中:
public class MerchantAccountBalanceRequest
{
[XmlElement("agent")]
public string Agent { get; set; }
[XmlElement("agentPin")]
public string AgentPin { get; set; }
}
public class RequestBody
{
[XmlElement("accountbalance")]
public MerchantAccountBalanceRequest BalanceRequest { get; set; }
}
[XmlRoot(ElementName = "Envelope")]
public class RequestEnvelope
{
[XmlElement("Body")]
public RequestBody Body { get; set; }
}
在序列化和反序列化时,请从XmlSerializer
而不是RequestEnvelope
构建MerchantAccountBalanceRequest
对象。在构造它们时,您必须设置RequestEnvelope.Body
和RequestBody.BalanceRequest
属性(您可以将Body
中的RequestEnvelope
属性初始化为新的RequestBody
实例。构造函数,为方便起见。)
这看起来像某个协议中的单个请求类型,因此如果您有多个请求类型,则可以为请求创建基类(例如RequestBase
),并调整RequestBody
以便它接受可能的请求元素的选择,如下例所示:
public abstract class RequestBase
{
}
public class SomeOtherRequest : RequestBase
{
[XmlElementAttribute("example")]
public string Example { get; set; }
}
public class MerchantAccountBalanceRequest : RequestBase
{
[XmlElement("agent")]
public string Agent { get; set; }
[XmlElement("agentPin")]
public string AgentPin { get; set; }
}
public class RequestBody
{
[XmlElement(ElementName = "accountbalance", Type = typeof(MerchantAccountBalanceRequest))]
[XmlElement(ElementName = "somethingelse", Type = typeof(SomeOtherRequest))]
public RequestBase Request { get; set; }
}