C# · 12月 26, 2021

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

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

例外:

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;

修改后的代码

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;

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