如何解决如何在C#中使用HttpClient验证XML数据
我是C#的新手,在验证API响应中的某些数据时遇到困难。
我需要导航到XML路径以使用返回值声明期望值。
这是我的代码:
[Test]
public void ValidatePostRequest()
{
XmlDocument doc = new XmlDocument();
doc.Load("X:\\xmlFile.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/PARENTNODE");
string requestNode = node.OuterXml;
using (HttpClient httpClient = new HttpClient())
{
HttpContent httpContent = new StringContent(requestNode,Encoding.UTF8,contentType);
Task<HttpResponseMessage> postResponse
= httpClient.PostAsync(postURL,httpContent);
HttpStatusCode statusCode = postResponse.Result.StatusCode;
HttpContent responseContent = postResponse.Result.Content;
string responseData = responseContent.ReadAsStringAsync().Result;
Task<String> resData = responseContent.ReadAsStringAsync();
string data = resData.Result;
Console.WriteLine("Getting Status Code: " + (int)statusCode);
Console.WriteLine("Returning body data: " + data.ToString());
//Need to verify the value returned in response for StatusMsgsCode
XmlNode msgStatusXMLNode = doc.DocumentElement.SelectSingleNode("/Trans/Output/ACORD/HomeLineBusiness/Construction/StatusMessage/StatusMsgCode");
//XmlNodeList msgStatusCd = doc.DocumentElement.GetElementsByTagName("/Trans/Output/ACORD/HomeLineBusiness/Construction/StatusMessage/StatusMsgCode");
if (msgStatusXMLNode != null)
{
Console.WriteLine(msgStatusXMLNode.InnerText);
}
else
{
Console.WriteLine("No value returned");
}
}
}
解决方法
这是对我有用的解决方案。用于在提取节点详细信息后验证xml数据。
[Test]
public void ValidatePostRequest()
{
//Load the payload for POST request from XML file
XmlDocument doc = new XmlDocument();
doc.Load("C:\\XMLFile.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/ParentNode");
string requestNode = node.OuterXml;
using (HttpClient httpClient = new HttpClient())
{
HttpContent httpContent = new StringContent(requestNode,Encoding.UTF8,contentType);
Task<HttpResponseMessage> postResponse
= httpClient.PostAsync(postURL,httpContent);
//Gets the statusCode for POST response
HttpStatusCode statusCode = postResponse.Result.StatusCode;
HttpContent responseContent = postResponse.Result.Content;
);
Task<String> resData = responseContent.ReadAsStringAsync();
//Response body is saved in string format
string data = resData.Result;
// Conversion of String to XML Node
XmlDocument document = new XmlDocument();
document.LoadXml(data);
XmlNode newNode = document.DocumentElement;
// Navigate to the node path for data extraction
XmlNode msgStatusNode = newNode.SelectSingleNode("/Parent/ChildNode1/Node1");
if (msgStatusNode != null)
{
Console.WriteLine(msgStatusNode.InnerText);
}
else
{
Console.WriteLine("Returning null");
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。