2010-07-04 158 views

回答

22

負載字符串:

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")); 
} 
+1

我得到一個錯誤,說明文檔沒有XPathSelectElement方法。我可能會做錯什麼? – 2010-07-04 19:17:18

+2

@Sergio Tapia,這是一個XML LINQ擴展方法:http://msdn.microsoft.com/en-us/library/bb156083.aspx 它需要添加'使用System.Xml.Linq'導入。 – Elisha 2010-07-04 19:19:18

+2

你還需要'使用System.Xml.XPath;' – wisbucky 2013-06-21 23:13:47

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

40

爲什麼複雜的東西?這個作品:

var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253"); 
+0

'DownloadStringAsync'如何?是更好的方式來處理下載? – Ahmad 2016-01-01 13:22:51