1.Postman测试如下,对应返回xml文件节点结构如图所示:
2.代码实现:
/// <summary>
/// 调用WebService服务获取农业部数据 推送到中间库
/// </summary>
public class WebSvcCaller
{
public static void Start()
{
try
{
Console.WriteLine("------------- 调用WebService服务获取农业部数据-------------");
HttpClient httpClient = new HttpClient();
string url = "http://202.127.45.194/sofn-dgap-pre/ws/dataExport?wsdl&token=dgapWsdlToken66321";
IRepository<ProduceClassifyEntity> produceClassifyEntity = new BaseRepository<ProduceClassifyEntity>(new TempMysqlContext());
List<ProduceClassifyEntity> produceClassifyList = new List<ProduceClassifyEntity>();
//param.txt为请求post方法传递的xml
HttpResponseMessage response = httpClient.PostAsync(url, new StringContent(File.ReadAllText("param.txt"))).Result;
//请求接收参数
var result = response.Content.ReadAsStringAsync().Result;
//判断返回参数是否成功
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("请求WebService服务成功!");
XmlDocument xml = new XmlDocument();
xml.LoadXml(result);
XmlNamespaceManager nsp = new XmlNamespaceManager(xml.NameTable); //导入命名空间
nsp.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsp.AddNamespace("ns2", "http://ws.sofn.com/");
string snode = "/soap:Envelope/soap:Body/ns2:getDataResponse/return/data";
XmlNodeList nodelist = xml.SelectNodes(snode, nsp);
Console.WriteLine("数据总条数为:" + nodelist.Count + "条");
var index = 1;
foreach (XmlNode item in nodelist)
{
Console.WriteLine("正在执行第" + index++ + "行数据");
ProduceClassifyEntity pcEntity = new ProduceClassifyEntity();
XmlNodeList nodelist2 = item.SelectNodes("fieldsData");
foreach (XmlNode item2 in nodelist2)
{
if (item2.SelectSingleNode("columnName").InnerText.Trim() == "ID")
{
if (!string.IsNullOrEmpty(item2.SelectSingleNode("value")?.InnerText))
pcEntity.ID = item2.SelectSingleNode("value").InnerText.Trim();
else
pcEntity.ID = "无";
}
//.......此处省略对其他字段处理。
}
produceClassifyList.Add(pcEntity);
}
produceClassifyEntity.CreateManys(produceClassifyList);
Console.WriteLine("执行完成!");
}
else
{
Console.WriteLine("请求失败!");
}
}
catch (Exception ex)
{
throw new Exception($"执行程序发生异常:{ex.GetExceptionMsg()}");
}
}
}