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

14.4k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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);
0
On

Try this. This will load current date and time for every forecast:

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(XMLDocumentPath);
XmlNodeList NodeList = XMLDoc.SelectNodes("/xml_api_reply/weather/forecast_information/");
foreach(XmlNode Node in NodeList)
{
string DTime = Node["current_date_time"].InnerText;
//Do something with DTime
}