给定此URL:
http://www.dreamincode.net/forums/xml.php?showuser=1253
我该如何下载生成的XML文件并将其加载到内存中,以便使用Linq从中获取信息?
谢谢帮助。
给定此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"));
}
using System.Xml.Linq
。 - Elishausing System.Xml.XPath;
。 - wisbuckyWebClient 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
中。
DownloadStringAsync
怎么样?是处理下载的更好方法吗? - Ahmad