我目前正在创建一个API,它接受像“sample input”这样的字符串作为输入参数。此API应该调用其他第三方API传递与输入相同的值,如
https://thirdpartyhost/api/dept?name=sample+input
返回xml,如
<lab:labs>
<lab uri="https://thirdpartyhost/api/dept/1">
<name>sample input</name></lab>
</lab:labs>
我需要从<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;
}
}
我不确定如何从API的响应中提取uri。非常感谢任何帮助
答案 0 :(得分:1)
使用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();
答案 1 :(得分:1)
试试这个:
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();
}
}
replace将删除您未使用的命名空间,xmlString是您的responseString。