如何使用C#下载XML文件?

15
3个回答

42

为什么要把事情弄复杂呢?这个方法可以解决问题:

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

DownloadStringAsync 怎么样?是处理下载的更好方法吗? - Ahmad

25

加载字符串:

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
我遇到了一个错误,说doc没有XPathSelectElement方法。我可能做错了什么? - Sergio Tapia
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

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 中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接