鉴于此URL:
http://www.dreamincode.net/forums/xml.php?showuser=1253
如何下载生成的XML文件并将其加载到内存中以便我可以使用Linq从中获取信息?
感谢您的帮助。
答案 0 :(得分:40)
为什么复杂化?这有效:
var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253");
答案 1 :(得分:24)
加载字符串:
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"));
}
答案 2 :(得分:4)
您可以使用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
。