我尝试下面的代码来获取特定节点的值,但是在加载xml时抛出了这个异常:
例外:
Data at the root level is invalid. Line 1,position 1.
<?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;
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.")
解决方法
你的代码中的问题是xml.LoadXml(filePath);
LoadXml method take parameter as xml data not the xml file path
尝试这段代码
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; }
编辑
看到你的问题的最后一个编辑我找到了解决方案,
只需更换下面的2行
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.")
同
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;