2010-07-04 3 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. Что я могу сделать неправильно? –

+2

@Sergio Tapia, это метод расширения XML LINQ: http://msdn.microsoft.com/en-us/library/bb156083.aspx Ему нужно добавить 'using System.Xml.Linq' для импорта. – Elisha

+2

вам также нужно 'using System.Xml.XPath;' – wisbucky

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