代码之家  ›  专栏  ›  技术社区  ›  Sergio Tapia

如何使用c_下载XML文件?

  •  14
  • Sergio Tapia  · 技术社区  · 15 年前

    给定此URL:

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

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

    谢谢你的帮助。

    3 回复  |  直到 13 年前
        1
  •  24
  •   Elisha    15 年前

    加载字符串:

    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"));
    }
    
        2
  •  40
  •   Gabe Timothy Khouri    15 年前

    为什么事情复杂化?这工作:

    var xml = XDocument.Load("http://www.dreamincode.net/forums/xml.php?showuser=1253");
    
        3
  •  4
  •   Oded    15 年前

    你可以使用 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 .