How to get XML data from URL in c#.

For retrieving value from url and save as xml in format can be done by c#. I have given below code that will take website url as input parameter and return in xml form data .

Make Sure you have used: Used name space: using System.Net;

        /// <summary>
        ///  Get Data in xml format by url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static XmlDocument GetXmlDataFromUrl(string url)
        {

            //requesting the particular web page
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);

            //geting the response from the request url
            var response = (HttpWebResponse)httpRequest.GetResponse();

            //create a stream to hold the contents of the response (in this case it is the contents of the XML file
            var receiveStream = response.GetResponseStream();

            //creating XML document
            var mySourceDoc = new XmlDocument();

            //load the file from the stream
            mySourceDoc.Load(receiveStream);

            //close the stream
            receiveStream.Close();

            return mySourceDoc;
        }

Page Keyword: How to get xml data by c#. Get data from Url by c#.Get date in xml format from url in c#.

Advertisements

2 thoughts on “How to get XML data from URL in c#.

  1. It’s a really very informative information. It’s very useful and knowledgeable for me. i was stuck while coding this. I will bookmark this page for coding help.

    • How about doing it this way, slightly less code (excluding exception catching)

      private XmlDocument GetXmlDataFromUrl_v2(string url)
      {
      // open stream to the xml document
      //
      XmlTextReader reader = new XmlTextReader(textBox_Url.Text);
      XmlDocument doc = new XmlDocument();

      try
      {
      // read xml into document
      doc.Load(reader);
      reader.Close();
      }
      catch (Exception ex)
      {
      MessageBox.Show(ex.Message, “Exception”, MessageBoxButtons.OK, MessageBoxIcon.Error);
      }

      return doc;
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s