我尝试了以下代码来获取特定节点的值,但是在加载xml时会引发此异常:
例外:
根级别的数据无效。第1行,位置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;
修改后的代码
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
方法将参数作为xml数据而不是xml文件路径
试试这个代码
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;
}
编辑
看到您对问题的最后修改后,我找到了解决方案,
只需替换下面的两行
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;
它应该可以解决您的问题,或者您可以使用我之前提供的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句