本文介绍了如何获得字符串的XML节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过下面的代码来获取特定节点的值,但在加载此抛出异常的XML:



例外:



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;

Modified 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.")
解决方案

The problem in your code is xml.LoadXml(filePath);

Try this code

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

Edit

Seeing the last edit of your question i found the solution,

just replace the below 2 line

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.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

it should solve your problem or you can use the solution i provided earlier.

这篇关于如何获得字符串的XML节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 23:41
查看更多