I tried the below code to get the value of a particular node, but while loading the xml this exception is thrown:
Exception:
Data at the root level is 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 to an instance of an object.")
The problem in your code is xml.LoadXml(filePath);
LoadXml
method take parameter as xml data not the xml file path
Try this 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 the last edit of your question i found the solution,
Just replace the below 2 lines
XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall"); string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")
with
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;
It should solve your problem or you can use the solution i provided earlier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With