我正在尝试使用XML反序列化将XML响应从主机转换为C#对象。根元素将被转换为其对象,而第二元素将被转换,但无论如何它都是一个空元素。除此之外,没有其他元素被转换。我想念什么?
我为每个元素和元素数组尝试了许多不同的对象变体(即使不需要数组。我什至发现您可以将XML粘贴到Visual Studio的编辑器中,它将创建序列化的对象(编辑,粘贴特殊的XML(作为类粘贴),但是我什么都做不了!
这是XML的外观:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite/DTD MySite PaymentService v1//EN" "http://dtd.mysite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
<reply>
<orderStatus orderCode="ExampleOrder1">
<reference id="YourReference">https://payments-test.mysite.com/app/hpp/integration/wpg/corporate?OrderKey=NGPPTESTMERCH1%5Ejsxml3835829684&Ticket=00146321872957902pqKhCTUf0vajKCw-X5HqZA</reference>
</orderStatus>
</reply>
</paymentService>
-或-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//MySite//DTD MySite PaymentService v1//EN" "http://dtd.MySite.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="ExampleCode1">
<reply>
<orderStatus orderCode="ExampleOrder1">
<error code="2">
<![CDATA[Invalid address: Postal code is missing or empty.]]>
</error>
</orderStatus>
</reply>
</paymentService>
这里是对象:
[Serializable]
[XmlRoot(ElementName = "paymentService")]
public partial class PaymentResponse
{
[XmlAttribute()]
public string version { get; set; }
[XmlAttribute()]
public string merchantCode { get; set; }
[XmlElement("reply")]
public Reply reply { get; set; }
}
[Serializable]
public partial class Reply
{
[XmlElement("orderStatus")]
public OrderStatus orderStatus {get; set; }
}
[Serializable]
public partial class OrderStatus
{
[XmlAttribute()]
public string orderCode {get; set; }
[XmlElement(ElementName = "reference",IsNullable =true)]
public Reference reference {get; set; }
[XmlElement(ElementName = "error",IsNullable =true)]
public Error error {get; set; }
}
以下是进行反序列化的电话:
XmlSerializer serializer = new XmlSerializer(typeof(PaymentResponse));
PaymentResponse response = (PaymentResponse)serializer.Deserialize(reader);
从PaymentResponse返回的商家代码和版本中唯一的内容。
答案 0 :(得分:0)
您可能必须告诉序列化程序如何处理非基本类型。
尝试更改此内容
[XmlElement(ElementName = "reference",IsNullable =true)]
public Reference reference {get; set; }
[XmlElement(ElementName = "error",IsNullable =true)]
public Error error {get; set; }
对此
[XmlElement(ElementName = "reference", Type = typeof(Reference), IsNullable = true)]
public Reference reference {get; set; }
[XmlElement(ElementName = "error", Type = typeof(Error), IsNullable = true)]
public Error error {get; set; }
祝你好运!