-1

我有一个像这样的xml:

<RunResult>
  <PreviewRecords></PreviewRecords>
  <RecordsProcessed>100</RecordsProcessed>
  <LogError>false</LogError>
</RunResult>

我正在使用以下命令来获取节点的值RecordsProcessed

int NofRecords = 0;
NofRecords = Convert.ToInt32(xdRunResultDoc.Root.Element("RunResult").Element("RecordsProcessed").Value;

但是在这一行,它抛出异常“对象引用未设置为对象的实例”。

请建议我哪里出错了。

4

5 回答 5

2

xdRunResultDoc.Root已经指向<RunRdesult>元素,因此您不必Element("RunResult")再次调用。

我建议使用(int)cast onXElement而不是Convert.ToInt32XElement Explicit Conversion (XElement to Int32)

int NofRecords = (int)xdRunResultDoc.Root.Element("RecordsProcessed");
于 2013-08-26T06:00:09.580 回答
0

You can Find the solution by your self, Why don't you debug and see which causing "object reference not set to an instance of an object" error?

You can add watch to xdRunResultDoc and in the run time you can check what is root node and what you get for xdRunResultDoc.Root.Element("RunResult") etc..

Here your root node is RunResult you can't find Elements inside root node called RunResult

You better check this code project tutorial.

于 2013-08-26T06:12:51.900 回答
0

试试这个代码

从 xml 文件中读取整个文本并将其加载到 XmlDocument

XmlNode rootNode = xDoc.SelectSingleNode("RunResult");
                            if (rootNode.HasChildNodes)
                            {
                                foreach (XmlNode node in rootNode.ChildNodes)
                                {
                                    if (node.Name =="RecordsProcessed")
                                    {

                                        NofRecords=Convert.ToInt32(node.InnerText);
                                    }
                                }
                            }
于 2013-08-26T06:25:07.937 回答
0

尝试这个

int NofRcord = Convert.ToInt32(xdRunResultDoc.Root.Element("RecordsProcessed").Value);

有关详细信息,请参阅此链接http://msdn.microsoft.com/en-us/library/bb675196.aspx

于 2013-08-26T06:04:46.437 回答
0

这对我有用:

string xmlstring = @"<?xml version='1.0' encoding='utf-8'?>
    <RunResult>
        <PreviewRecords></PreviewRecords>
        <RecordsProcessed>100</RecordsProcessed>
        <LogError>false</LogError>
    </RunResult>";

System.Xml.Linq.XDocument doc = XDocument.Parse(xmlstring);

int NofRecords = 0;

NofRecords = Convert.ToInt32(doc.Element("RunResult").Element("RecordsProcessed").Value);
于 2013-08-26T06:10:58.617 回答