简体   繁体   中英

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. This API should be calling other third party API passing the same value we got as the input like

 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.

 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. Any help is greatly appreciated with this

Using AngleSharp , you can do as follows:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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