2010-07-04 16 views

risposta

22

carico stringa:

string xml = new WebClient().DownloadString(url); 

Poi caricare in XML:

XDocument doc = XDocument.Parse(xml); 

Ad esempio:

[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

Ricevo un errore che doc non ha un metodo XPathSelectElement. Cosa potrei fare di sbagliato? –

+2

@Sergio Tapia, È un metodo di estensione XML LINQ: http://msdn.microsoft.com/en-us/library/bb156083.aspx È necessario aggiungere 'utilizzando System.Xml.Linq' alle importazioni. – Elisha

+2

è necessario anche 'using System.Xml.XPath;' – wisbucky

4

È possibile utilizzare la classe 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(); 

pur usando DownloadString è più facile:

WebClient client = new WebClient(); 
string s = client.DownloadString("http://example.com"); 

È possibile caricare la stringa risultante in un XmlDocument.

40

Perché complicare le cose? Funziona:

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

E riguardo 'DownloadStringAsync'? è il modo migliore per gestire il download? – Ahmad

Problemi correlati