我尝试使用下面的代码来获取特定节点的值,但是在加载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>
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
修改代码
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.")
Run Code Online (Sandbox Code Playgroud)
Rez*_*oan 23
代码中的问题是 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;
}
Run Code Online (Sandbox Code Playgroud)
编辑
看到问题的最后一次编辑,我找到了解决方案,
只需更换以下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.")
Run Code Online (Sandbox Code Playgroud)
同
string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;
Run Code Online (Sandbox Code Playgroud)
它应该解决您的问题,或者您可以使用我之前提供的解决方案.