简体   繁体   English

如何从API的XML响应中提取uri

[英]How do I extract an uri out of a XML response from an API

I am currently creating an API which accepts the string like "sample input" as input parameter. 我目前正在创建一个API,该API接受诸如“ sample input”之类的字符串作为输入参数。 This API should be calling other third party API passing the same value we got as the input like 该API应该调用其他第三方API,并传递与输入类似的值

 https://thirdpartyhost/api/dept?name=sample+input

which returns an xml like 返回一个像

<lab:labs>
<lab uri="https://thirdpartyhost/api/dept/1">
 <name>sample input</name></lab>
</lab:labs>

I will need to retrieve the uri from the <lab uri="https://thirdpartyhost/api/dept/1"> which will give us the required response. 我将需要从<lab uri="https://thirdpartyhost/api/dept/1">检索uri,这将给我们所需的响应。

 public IHttpActionResult Get(string DeptName)
    {
        using (var client = new HttpClient())
        {
            string BaseURL = ConfigurationManager.AppSettings["BaseURL"];
            Uri uri = new Uri(BaseURL);
            client.BaseAddress = uri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            var response = client.GetAsync("api/v2/dept?name=" +LabName).Result;
            if (response.IsSuccessStatusCode)
            {
                string responseString = response.Content.ReadAsStringAsync().Result;
            }
        }

I am not sure how to extract the uri from the response from the API. 我不确定如何从API的响应中提取uri。 Any help is greatly appreciated with this 任何帮助都非常感谢

Using AngleSharp , you can do as follows: 使用AngleSharp ,您可以执行以下操作:

var xmlString = "<lab:labs><lab uri=\"https://thirdpartyhost/api/dept/1\"><name> sample input </name></lab></lab:labs>"
var parser = new HtmlParser();
var parsedXml = parser.Parse(xmlString);
var extractedUri = parsedXml.QuerySelectorAll("lab").Attr("uri").FirstOrDefault();

Try this: 尝试这个:

string xmlString = @"<lab:labs>
    <lab uri=""https://thirdpartyhost//api//dept//1"">
        <name>sample input</name></lab>
    </lab:labs>".Replace("lab:labs>", "labs>");

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
XmlNodeList nodes = doc.SelectNodes("labs//lab");

if (nodes != null && nodes.Count > 0)
{
    XmlNode node = nodes[0];
    if (node.Attributes["uri"] != null)
    {
        string uri = node.Attributes["uri"].Value.ToString();
    }
}

The replace will remove the namespace you are not using and xmlString is your responseString. 替换将删除您不使用的名称空间,而xmlString是您的responseString。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM