0

We have the following code that parses the XML file that is saved locally, how do I load the XML file that is hosted in the internet?

private void BindGrid()
{
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(Server.MapPath("~/test-xml-data.xml"));
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

I tried the following, but it throws an error saying

System.Web.HttpException: 'https:/www.w3schools.com/xml/cd_catalog.xml' is not a valid virtual path

    ds.ReadXml(Server.MapPath("https://www.w3schools.com/xml/cd_catalog.xml"));
janw
  • 8,758
  • 11
  • 40
  • 62
bickyz
  • 37
  • 2
  • 9
  • 1
    In ASP.NET the `Server.MapPath` returns the physical path of a specified virtual file, this means it can only be used to read files that satisfy 2 conditions: 1. Are on physical drives connected to the computer running the server, and 2. Are mapped to a virtual file. If you need to parse remote XML you'll need to download it first as described [here](https://stackoverflow.com/a/1048204/9363973) or (if you're directly creating an `XDocument`) like [so](https://stackoverflow.com/a/3175870/9363973) – MindSwipe Nov 09 '21 at 12:46
  • 1
    *how do I load the xml file that is hosted on internet* - you download it first, just like you would any other file. You can stream it into an xml reader if you don;t want to put it on your local disk, but you're still downloading it all the same.. Search "c# download file"? Modern code probably uses HttpClient rather than WebClient, btw – Caius Jard Nov 09 '21 at 12:49
  • 2
    You can create a XmlReader : XmlReader reader = XmlReader.Create("URL"). then use the read in the ReadXml : ds.ReadXml(reader); – jdweng Nov 09 '21 at 13:34
  • Have you tried jdweng's suggestion and has it worked? – Jiale Xue - MSFT Nov 11 '21 at 06:23

0 Answers0