【发布时间】:2010-10-13 07:37:47
【问题描述】:
有一些 php API 服务,当在查询字符串中发送一些参数时,它以 xml 格式返回日期。所以我想知道如何发送调用页面并在 c# .net 中取回结果。就像使用 xml 阅读器或 xml 方案一样?
【问题讨论】:
有一些 php API 服务,当在查询字符串中发送一些参数时,它以 xml 格式返回日期。所以我想知道如何发送调用页面并在 c# .net 中取回结果。就像使用 xml 阅读器或 xml 方案一样?
【问题讨论】:
您可以将 url 地址传递给 XmlReader:
using (var reader = XmlReader.Create("http://example.com/somexml"))
{
// TODO: parse
}
另一种可能是使用XDocument:
var doc = XDocument.Load("http://example.com/somexml");
// TODO: manipulate the document
还有一种可能是使用WebClient:
using (var client = new WebClient())
{
string xml = client.DownloadString("http://example.com/somexml");
// TODO: feed the xml to your favorite XML parser
}
【讨论】:
XmlReaderSettings。
如果参数在查询字符串中,这很容易...根据 Darin 的回答,我会使用 XmlReader.Create,然后为了便于使用 XML,我会使用 LINQ to XML:
XDocument doc;
using (var reader = XmlReader.Create("http://example.com/somexml"))
{
doc = XDocument.Load(reader);
}
// Now work with doc
(编辑:正如 Darin 所说,XDocument.Load(string uri) 使这更简单 - 忽略文档说它从 文件 加载数据的事实。)
如果您需要对事物的 HTTP 方面进行更多控制(例如,包含发布数据),您可以使用以下内容:
WebRequest request = WebRequest.Create(...);
// Fiddle with request here
XDocument doc;
using (WebResponse response = request.GetResponse())
using (Stream data = response.GetResponseStream())
{
doc.Load(data);
}
// Use doc here
请注意,这都是同步的 - 也可以异步解析,但需要做更多工作。
【讨论】:
更好的方法是
XmlDocument xdoc;
xdoc = new XmlDocument();
xdoc.Load(XmlReader.Create("weblink"));
无法分析 XDocument 并提取其 XML 值,这在 XmlDocument 中是可能的
【讨论】: