[英]How can I extract and get the values from this response in C#
這是我的代碼:
private void button1_Click(object sender, EventArgs e)
{
var process = new com.globalpay.certapia.GlobalPayments();
var response = process.ProcessCreditCard("xxxxxx", "xxxxxx", "Sale",
textBox1.Text, textBox2.Text, "", "", textBox3.Text, "",
"", "", "", "", "");
MessageBox.Show("RespMSG: " + response.RespMSG
+ "\nMessage: " + response.Message
+ "\nAuthCode: " + response.AuthCode
+ "\nPNRef: " + response.PNRef
+ "\nHostCode: " + response.HostCode
+ "\nCVResultTXT: " + response.GetCVResultTXT
+ "\nCommercialCard: " + response.GetCommercialCard
+ "\nExtData: " + response.ExtData);
}
輸出如下:
在ExtData中,我很困惑,我不知道如何提取那些值,例如獲取CardType,BatchNum,MID,TransID的值。
如何提取這些值?
任何建議或建議我將如何實現這將是一個很大的幫助。 謝謝!
基於api的文檔:
<?xml version="1.0" encoding="utf-8" ?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="GlobalPayments">
<Result>0</Result>
<RespMSG>Approved</RespMSG>
<Message>AP</Message>
<AuthCode>000014</AuthCode>
<PNRef>564286</PNRef>
<HostCode>0032</HostCode>
<GetCVResultTXT>Service Not Requested</GetCVResultTXT>
<GetCommercialCard>False</GetCommercialCard>
<ExtData>InvNum=1234567900,CardType=MasterCard,BatchNum=0011<BatchNum>0011
</BatchNum><ReceiptData><MID>4910354</MID><Trans_Id>MCC1421250315
</Trans_Id></ReceiptData></ExtData>
</Response>
這似乎是格式錯誤的響應的情況。 對於這類Web服務,這是很常見的。 不要指望它會很快好起來。
您只需要蠻力分析,並希望他們不要改變它,否則它會根據您得到的響應而改變。
通用算法為:
使用LINQ是最簡單的方法,假設響應是字符串或可以轉換為字符串的內容:
// XDocument.Parse will load a string into the XDocument object.
XDocument xDoc = XDocument.Parse(response);
// XNamespace is required in order to parse the document.
XNamespace ns = "GlobalPayments";
var resp = (from x in xDoc.Descendants(ns + "ExtData")
select new
{
ExtData = x.Value,
BatchNum = x.Element(ns + "BatchNum").Value,
MID = x.Element(ns + "MID").Value,
TransID = x.Element(ns + "TransID").Value
}).SingleOrDefault();
然后,您將獲得具有以下屬性的匿名類型( resp
):
resp.ExtData = "InvNum=1234567900,CardType=MasterCard,BatchNum=0011"
resp.BatchNum = "0011"
resp.MID = "4910354"
resp.TransID = "MCC1421250315"
然后,您可以對ExtData使用常規的String.Split操作來從所需的字符串中獲取數據。
不是最漂亮的解決方案,但有時您必須使用蠻力方法。 采用並修改以適合您的需求/口味。
您需要使用String.IndexOf ..),然后再使用String.SubString(..)等手動提取它們
var cardType = data.Substring(data.IndexOf("<BatchNum>"), data.IndexOf("</BatchNum>") - data.IndexOf("<BatchNum>"));
當然有一些例外情況處理代碼...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.