我嘗試下面的代碼以獲取特定節點的值,但在加載此拋出異常的XML:如何獲得在字符串中的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;
改進型Code
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.")
[根目錄下的數據無效]的可能重複(http://stackoverflow.com/questions/5748668/data-at-the-root-level-is-invalid) –
爲什麼不使用LINQ到XML?這比舊的'XmlDocument'類更容易和更友好。 – MarcinJuraszek