我有需要在c#对象中解析的XmL。 Xml有我的api密钥,我需要在我的c#控制器类中

时间:2017-07-11 15:08:29

标签: c# json xml parsing xml-parsing

我需要将xml转换为c#object

这是我尝试使用的xml api密钥

<?xml version="1.0" encoding="UTF-8"?>
<rsp stat="ok" version="1.0">
    <api_key>57173e1d727788c372e91c115e8e2ff6</api_key>
    <version>4</version>
</rsp>

C#类,我需要将该api用作对象 我从信息中取出了密码和api密钥。

public static string GetApiKey()
        {
            var client = new RestClient("https://pi.pardot.com/api/login/version/3");
            var request = new RestRequest(Method.POST);
            request.AddHeader("accept-charset", "utf-8");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded",  ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            //parse to get apikey

                return response.Content;
            string apikey = "";

            return apikey;
        }
    }

1 个答案:

答案 0 :(得分:1)

获得XML字符串后,这很简单。

  1. 解析XML。
  2. 从XML获取rsp元素。
  3. api_key元素中获取rsp元素。
  4. 获取api_key元素的Value属性。
  5. 像这样:

     var xml = response.Content;
     var apiKey = XDocument.Parse(xml).Element("rsp").Element("api_key").Value;