[英]How can I download an XML file using C#?
鉴于此URL:
http://www.dreamincode.net/forums/xml.php?showuser=1253
如何下载生成的XML文件并将其加载到内存中以便我可以使用Linq从中获取信息?
谢谢您的帮助。
为什么复杂的事情? 这有效:
var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253");
加载字符串:
string xml = new WebClient().DownloadString(url);
然后加载到XML:
XDocument doc = XDocument.Parse(xml);
例如:
[Test]
public void TestSample()
{
string url = "http://www.dreamincode.net/forums/xml.php?showuser=1253";
string xml;
using (var webClient = new WebClient())
{
xml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(xml);
// in the result profile with id name is 'Nate'
string name = doc.XPathSelectElement("/ipb/profile[id='1253']/name").Value;
Assert.That(name, Is.EqualTo("Nate"));
}
您可以使用WebClient
类:
WebClient client = new WebClient ();
Stream data = client.OpenRead ("http://example.com");
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
虽然使用DownloadString
更容易:
WebClient client = new WebClient ();
string s = client.DownloadString("http://example.com");
您可以将生成的字符串加载到XmlDocument
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.