Extract a Single Node from XML String#

I was asked the other day how to extract a single node value from a string of XML and threw together a quick piece of code to do it.

private void Page_Load(object sender, System.EventArgs e)

{

string xmlstr= @"

<statistics>

<gather>66400</gather>

<user_count>666452</user_count>

<user_demand>23.83</user_demand>

</statistics>";

XmlDocument doc = new XmlDocument();

doc.LoadXml(xmlstr);

XmlNode node = doc.SelectSingleNode("statistics/user_count");

Label1.Text = node.InnerText;

}

The code simply loads the XML string verbatim into an XmlDocument object, which can then simply be  parsed using an XPath selectSingleNode query and slapped into a label control.

If however you have a few entries that are the same in your XML, and you want specific one you can use a use a positional predicate to get the node.

string xmlstr = @"

<statistics>

<gather>66400</gather>

<user_count>666451</user_count>

<user_demand>23.83</user_demand>

<gather>66401</gather>

<user_count>666452</user_count>

<user_demand>23.83</user_demand>

<gather>66402</gather>

<user_count>666453</user_count>

<user_demand>23.83</user_demand>

</statistics>";

XmlDocument doc = new XmlDocument();

doc.LoadXml(xmlstr);

XmlNode node = doc.SelectSingleNode("statistics/user_count[3]");

Label1.Text = node.InnerText;

 

11/1/2006 3:20:53 PM (GMT Standard Time, UTC+00:00) #    Comments  |  Trackback

 

Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

All content © 2009, John Timney
On this page
This site
Calendar
<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567
Archives
Sitemap
Blogroll OPML
Talk to Me

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail