我正在尝试反序列化XML。 示例XML如下所示
[XmlType("TRANSACTION_RESPONSE")]
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
以下是班级
BankQueryResponse result = new BankQueryResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(BankQueryResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (BankQueryResponse) serializer.Deserialize(xmlreader);
}
}
反序列化代码是
public string textbox1Value = "";
public string textbox2Value = "";
我将结果中的所有值都设为null。我不确定是什么原因。有人可以解决这个问题。在反序列化时我错过了什么
答案 0 :(得分:5)
你应该像这样修改代码
[XmlType("TRANSACTION_RESPONSE")]
public class TransactionResponse
{
[XmlElement("TRANSACTION")]
public BankQueryResponse Response { get; set; }
}
这会像这样改变
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
Deseralization Code就是这样的
TransactionResponse result = new TransactionResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(TransactionResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (TransactionResponse) serializer.Deserialize(xmlreader);
}
}