Reading an XML Feed into XElement
-
27-10-2019 - |
Question
I have an Xml Stream that I'd like to read into an XElement
. I've seen samples that use XmlTextReader
but I need it in an XElement
.
The code that I have so far:
string url =
String.Format( "http://dev.virtualearth.net/REST/v1/Locations/{0}?o=xml&key={1}", HttpUtility.UrlEncode( AddressQuery ), mapkey );
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
XmlTextReader reader = new XmlTextReader( url );
I'm just not sure how to get the reader into an XElement. Perhaps I'm going about it the wrong way.
Solution
with linq to xml you can simply do this
var xml = XElement.Load(uri);
OTHER TIPS
You've only created an instance of WebRequest
- this doesn't actually ask the server to download the contents of the URL. Calling WebRequest.GetResponse()
should download the contents of the URL from the server. The MSDN page for WebRequest has an example of downloading the contents of a URL.
Once you have the response, you can call XDocument.Load() and pass it the response stream (by calling GetResponseStream()
from the response object). The XDocument
class has methods to retrieve an XElement
in the XML document.