从 Xml 响应中获取特定元素值 (RestSharp/C#)

Obtain Specific Element Value From Xml Response (RestSharp/C#)

我有此代码,其中 returns 一个 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>07675018324500$</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 标签,这可能会导致解析问题。当涉及到selecting你要找的节点时,你可以将selection字符串设置为如下,

XmlNode node = root.SelectSingleNode("/nm_response/transaction/cc_number")

这应该 select 您要查找的特定节点,并允许您使用以下内容获取内部文本。

String cc_Number = node.InnerText;