如何解决从 Xml 响应中获取特定元素值 (RestSharp/C#)
我有这个代码,它为我的请求和响应返回一个 RestSharp 对象:
var request = new RestRequest(Method.POST);
request.AddParameter("Content-Type","application/xml",ParameterType.HttpHeader);
request.AddParameter("security_key",apiKey,ParameterType.QueryString);
request.AddParameter("transaction_id",transactionDetailsResource.TransactionId,ParameterType.QueryString);
request.RequestFormat = DataFormat.Xml;
response = client.Execute(request) as RestResponse;
然后我有一个包含以下代码的方法来获取我需要的元素:
public static TransactionDetailsDto convertContent(RestResponse response){
TransactionDetailsDto tranDto = new TransactionDetailsDto();
XmlDocument doc = new XmlDocument();
doc.LoadXml(response.Content);
XmlElement root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode("/cc_number");
tranDto.maskedCCNumber = node.Value;
tranDto.response = response.Content;
return tranDto;
}
我可以在调试器中看到 response.Content
确实有 XML。我通过 XmL 指定了请求对象格式其数据。但是当我得到一行以获得特定值时,我看到一个空值。我不确定从这里去哪里。
我认为此行代码不正确:
XmlNode node = root.SelectSingleNode("/cc_number");
这是 response.Content
xml 的上半部分,其中包含我所追求的元素和值:
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><nm_response><transaction><transaction_id>5432920844</transaction_id><partial_payment_id></partial_payment_id><partial_payment_balance></partial_payment_balance><platform_id>54e69fa3-36af-ea11-8ada-0050569419e2</platform_id><transaction_type>cc</transaction_type><condition>complete</condition><order_id>54e69fa3-36af-ea11-8ada-0050569419e2</order_id><authorization_code>857882</authorization_code><ponumber></ponumber><order_description></order_description><first_name></first_name><last_name>07675018324$02500$</last_name><address_1></address_1><address_2></address_2><company></company><city></city><state></state><postal_code>30041</postal_code><country></country><email></email><phone></phone><fax></fax><cell_phone></cell_phone><customertaxid></customertaxid><customerid></customerid><website></website><shipping_first_name></shipping_first_name><shipping_last_name></shipping_last_name><shipping_address_1></shipping_address_1><shipping_address_2></shipping_address_2><shipping_company></shipping_company><shipping_city></shipping_city><shipping_state></shipping_state><shipping_postal_code></shipping_postal_code><shipping_country></shipping_country><shipping_email></shipping_email><shipping_carrier></shipping_carrier><tracking_number></tracking_number><shipping_date></shipping_date><shipping>0.00</shipping><shipping_phone></shipping_phone><cc_number>4xxxxxxxxxxx7254</cc_number>
解决方法
确保您拥有有效的 xml 数据,因为您提供的数据缺少可能导致解析问题的关闭交易和 nm_response 标记。在选择要查找的节点时,可以将选择字符串设置为如下,
XmlNode node = root.SelectSingleNode("/nm_response/transaction/cc_number")
这应该选择您要查找的特定节点,并允许您使用以下内容获取内部文本。
String cc_Number = node.InnerText;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。