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

Ser*_*pia 15 .net c# xml

鉴于此URL:

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

如何下载生成的XML文件并将其加载到内存中以便我可以使用Linq从中获取信息?

谢谢您的帮助.

Gab*_*abe 40

为什么复杂的事情?这有效:

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


Eli*_*sha 24

加载字符串:

string xml = new WebClient().DownloadString(url);
Run Code Online (Sandbox Code Playgroud)

然后加载到XML:

XDocument doc = XDocument.Parse(xml);
Run Code Online (Sandbox Code Playgroud)

例如:

[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"));
}
Run Code Online (Sandbox Code Playgroud)

  • @Sergio Tapia,这是一个XML LINQ扩展方法:http://msdn.microsoft.com/en-us/library/bb156083.aspx它需要将`using System.Xml.Linq`添加到导入. (2认同)
  • 你还需要`使用System.Xml.XPath;` (2认同)