Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download an XML file using C#?

Tags:

c#

.net

xml

Given this URL:

http://www.dreamincode.net/forums/xml.php?showuser=1253

How can I download the resulting XML file and have it loaded to memory so I can grab information from it using Linq?

Thanks for the help.

like image 215
Sergio Tapia Avatar asked Jul 04 '10 18:07

Sergio Tapia


3 Answers

Why complicate things? This works:

var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253");
like image 164
Gabe Avatar answered Sep 21 '22 14:09

Gabe


Load string:

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

Then load into XML:

XDocument doc = XDocument.Parse(xml);

For example:

[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"));
}
like image 36
Elisha Avatar answered Sep 22 '22 14:09

Elisha


You can use the WebClient class:

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 ();

Though using DownloadString is easier:

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

You can load the resulting string into an XmlDocument.

like image 45
Oded Avatar answered Sep 22 '22 14:09

Oded