我有一个远程托管的XML SOAP消息,我需要在ASP.NET MVC C#Web应用程序中阅读。我是上述所有技术的新手,所以请放轻松。
下面的架构。
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetMetalQuoteResponse xmlns="http://.../...">
<GetMetalQuoteResult>
<Type>string</Type>
<Currency>string</Currency>
<Date>Date</Date>
<Time>Time</Time>
<Rate>decimal</Rate>
<Bid>decimal</Bid>
<BidTime>Time</BidTime>
<ExpTime>DateTime</ExpTime>
<DisplayTime>Time</DisplayTime>
<DisplayDate>Date</DisplayDate>
<Ask>Decimal</Ask>
<AskTime>Time</AskTime>
</GetMetalQuoteResult>
</GetMetalQuoteResponse>
</soap:Body>
</soap:Envelope>
目前,我的控制器中有以下代码。
var xml = XElement.Load(url);
System.Diagnostics.Debug.WriteLine("");
foreach (XElement x in xml.Nodes())
{
System.Diagnostics.Debug.WriteLine(x.Name + ":\n"+ x.Value);
}
System.Diagnostics.Debug.WriteLine("");
但这只会返回以下内容:
{http://schemas.xmlsoap.org/soap/envelope/}
Body:XAUGBP5/22/201212:21:04 PM1000.86251000.862512:21:04 PM2012 May 22 12:21 PM BST1:21:04 PM EDT05/22/121001.249412:21:04 PM
我需要它单独返回:
Type: XAU
Currency: GBP
Date: 5/22/201212:21:04
....
....
提前感谢您的帮助。
答案 0 :(得分:2)
一个好的选择可能是生成客户端代理类。您可以通过在Visual Studio中添加服务引用或使用wsdl.exe命令行工具来执行此操作。这样,您可以调用该方法并将结果作为常规C#对象接收,而无需过多担心SOAP基础结构。
拥有客户端代理后,您可以编写如下所示的代码:
var client = new ServiceReference.ServiceClient();
var result = client.GetMetalQuote();
System.Diagnostics.Debug.WriteLine(result.GetMetalQuoteResult.Currency);
// etc.
答案 1 :(得分:0)
您可以使用它来获得结果:
var result = root1.Descendants()
.First(x => x.Name.LocalName == "GetMetalQuoteResult")
.Elements()
.Select(x => new { Name = x.Name.LocalName, Value = x.Value })
.ToArray();
获取结果值:
foreach(var x in result)
System.Diagnostics.Debug.WriteLine(x.Name + ": "+ x.Value);
答案 2 :(得分:0)
string url = "http://www..../...";
var xml = XElement.Load(url);
XNamespace ns = "http://.../...";
var results =
from result in xml.Descendants(ns + "GetMetalQuoteResult")
select new SpotPriceModel
{
Type = result.Element(ns + "Type").Value,
Currency = result.Element(ns + "Currency").Value,
...
...
Ask = (decimal)result.Element(ns + "Ask"),
AskTime = result.Element(ns + "AskTime").Value
};
var spot = results.First();
System.Diagnostics.Debug.WriteLine("\n\nASK:\t" + spot.Ask + "\n\n");
return View(spot);
}