c# - How to get the xml node value in string -
i tried below code value of particular node, while loading xml exception thrown:
exception:
data @ root level invalid. line 1, position 1.
xml
<?xml version="1.0"?> <data xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <date>11-07-2013</date> <start_time>pm 01:37:11</start_time> <end_time>pm 01:37:14</end_time> <total_time>00:00:03</total_time> <interval_time/> <worked_time>00:00:03</worked_time> <short_fall>08:29:57</short_fall> <gain_time>00:00:00</gain_time> </data>
c#:
xmldocument xml = new xmldocument(); filepath = @"d:\work_time_calculator\10-07-2013.xml"; xml.loadxml(filepath); // exception occurs here xmlnode node = xml.selectsinglenode("/data[@*]/short_fall"); string id = node["short_fall"].innertext;
modified code
c#:
xmldocument xml = new xmldocument(); filepath = @"d:\work_time_calculator\10-07-2013.xml"; xml.load(filepath); xmlnode node = xml.selectsinglenode("/data[@*]/short_fall"); string id = node["short_fall"].innertext; // exception occurs here ("object reference not set instance of object.")
the problem in code xml.loadxml(filepath);
loadxml method take parameter xml data not xml file path
try code
string xmlfile = file.readalltext(@"d:\work_time_calculator\10-07-2013.xml"); xmldocument xmldoc = new xmldocument(); xmldoc.loadxml(xmlfile); xmlnodelist nodelist = xmldoc.getelementsbytagname("short_fall"); string short_fall=string.empty; foreach (xmlnode node in nodelist) { short_fall = node.innertext; }
edit
seeing last edit of question found solution,
just replace below 2 line
xmlnode node = xml.selectsinglenode("/data[@*]/short_fall"); string id = node["short_fall"].innertext; // exception occurs here ("object reference not set instance of object.")
with
string id = xml.selectsinglenode("data/short_fall").innertext;
it should solve problem or can use solution provided earlier.
Comments
Post a Comment