XML序列化,其中request元素包含多个父元素

时间:2015-04-06 09:49:23

标签: c# .net xml xml-serialization xml-deserialization

我有一个商家帐户余额请求类,如下所示:

[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>

也就是说,只需使用EnvelopeBody元素进行包装。

1 个答案:

答案 0 :(得分:1)

虽然您无法通过请求类的属性实现此目的,但您可以将请求包含在代表EnvelopeBody元素的其他类中:

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.BodyRequestBody.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; }
}