鑑於這種網址:如何使用C#下載XML文件?
http://www.dreamincode.net/forums/xml.php?showuser=1253
如何下載生成的XML文件並將其加載到內存中,因此我可以使用LINQ抓住從它的信息?
感謝您的幫助。
鑑於這種網址:如何使用C#下載XML文件?
http://www.dreamincode.net/forums/xml.php?showuser=1253
如何下載生成的XML文件並將其加載到內存中,因此我可以使用LINQ抓住從它的信息?
感謝您的幫助。
負載字符串:
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
。
爲什麼複雜的東西?這個作品:
var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253");
'DownloadStringAsync'如何?是更好的方式來處理下載? – Ahmad 2016-01-01 13:22:51
我得到一個錯誤,說明文檔沒有XPathSelectElement方法。我可能會做錯什麼? – 2010-07-04 19:17:18
@Sergio Tapia,這是一個XML LINQ擴展方法:http://msdn.microsoft.com/en-us/library/bb156083.aspx 它需要添加'使用System.Xml.Linq'導入。 – Elisha 2010-07-04 19:19:18
你還需要'使用System.Xml.XPath;' – wisbucky 2013-06-21 23:13:47