Search code examples
c#.netxml

How to get the xml node value in string


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.")

Solution

  • 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.