How do I find a XML element using c# when I know the exact path?

Richard Walton picture Richard Walton · Aug 10, 2012 · Viewed 11.3k times · Source

How do I get information from an xml document? I have an xml document at c:\temp\data.xml and am using visual studio.

The closest I can figure is:

XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"C:\temp\data.xml");
date = xdoc.SelectSingleNode("/forcast_informat…

The XML document looks like this:

<?xml version="1.0"?>
-<xml_api_reply version="1">
    -<weather section="0" row="0" mobile_zipped="1" mobile_row="0" tab_id="0" module_id="0">
        -<forecast_information>
             etc etc...
             <current_date_time data="2012-08-09 21:53:00 +0000"/>
             etc, etc...

All I want to do is grab that date of 2012-08-09 21:53:00 +0000...any suggestions?

Answer

Daniel Gabriel picture Daniel Gabriel · Aug 10, 2012

This should do the trick:

XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"C:\temp\data.xml");
XmlNode dataAttribute = xdoc.SelectSingleNode("/xml_api_reply/weather/forecast_information/current_date_time/@data");

Console.WriteLine(dataAttribute.Value);