Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, 17 December 2008

XPath in C#

string url = "http://www.example.com/somedata.xml";

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());

string xmlstr = sr.ReadToEnd();

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlstr);

XmlNode root = doc.DocumentElement;

// Get a single node
XmlNode tnode = root.SelectSingleNode("/FEED/SOURCE");

// Get all nodes that match a certain XPath expression
XmlNodeList alltitles = root.SelectNodes("/BOOK/TITLE");

There is a useful table of XPath syntax on this page.

Wednesday, 26 November 2008

Best method to read a web page into a string in C#

There are a number of ways to get the contents of a web page (or xml document such as an RSS feed) into a string in C#.

Unless someone can show me an even shorter method, I think the least lines of code way to do this is using the WebClient class in the System.Net namespace as follows:

WebClient client = new WebClient();
string pageContents = client.DownloadString(url);

Job done!

Note that this is much shorter than the method you're most likely to find on Google which is to build a web request then process the resulting response stream into a string using a StreamReader as in the below example. This works but is a lot more lines of code and creation of unnecessary objects.

using System;
using System.IO;
using System.Net;
using System.Text;

public static void GetFile(string strURL, string strFilePath)
{
WebRequest myWebRequest = WebRequest.Create(strURL);
WebResponse myWebResponse = myWebRequest.GetResponse();

Stream ReceiveStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream =
new StreamReader( ReceiveStream, encode );
string strResponse = readStream.ReadToEnd();

readStream.Close();
myWebResponse.Close();

}