如何获取字符串中的xml节点值

我尝试了下面的代码来获取特定节点的值,但是在加载xml时抛出了这个exception:

例外:

根级别的数据无效。 第1行,第1位。

XML

  11-07-2013 PM 01:37:11 PM 01:37:14 00:00:03  00:00:03 08:29:57 00:00:00  

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; } 

编辑

看到问题的最后一次编辑,我找到了解决方案,

只需更换以下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; 

它应该可以解决您的问题,或者您可以使用我之前提供的解决方案。

你应该使用.Load而不是.LoadXML

MSDN链接

“LoadXml方法用于直接加载XML字符串。您希望使用Load方法。”

ref: 链接

 XmlDocument d = new XmlDocument(); d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml"); XmlNodeList n = d.GetElementsByTagName("Short_Fall"); if(n != null) { Console.WriteLine(n[0].InnerText); //Will output '08:29:57' } or you could wrap in foreach loop to print each value XmlDocument d = new XmlDocument(); d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml"); XmlNodeList n = d.GetElementsByTagName("Short_Fall"); if(n != null) { foreach(XmlNode curr in n) { Console.WriteLine(curr.InnerText); } }