Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get XML values using foreach

I want to get the subdata and subdata2 values using foreach, but for some reason, I get a null reference exception.

Xml:

<project>
<name>Name1</name>
<data>
    <subdata>1</subdata>
    <subdata2>1</subdata2>
</data>
<data>
    <subdata>3</subdata>
    <subdata2>2</subdata2>
</data>
</project>

Code:

XmlNode datanode = doc.DocumentElement.SelectSingleNode("/project/data");
XmlNode innerDataNode;
foreach (XmlNode dataVar in datanode)
{
    innerDataNode = datanode.SelectSingleNode("/subdata");
    int subdataVal = XmlConvert.ToInt16(innerDataNode.InnerText);
    //(...)
}

Exception:

System.NullReferenceException: 'Object reference not set to an instance of an object. innerDataNode was null.

What am I doing wrong?

like image 469
Laszlo Avatar asked Feb 04 '26 05:02

Laszlo


1 Answers

You're not searching in the current context of the node. The difference is only a dot. So

innerDataNode = datanode.SelectSingleNode("/subdata");

Should be:

innerDataNode = datanode.SelectSingleNode("./subdata");

It's a small mistake, happens to a lot of us. But that doesn't seem to be your only mistake:

XmlNode datanode = doc.DocumentElement.SelectSingleNode("/project/data");

Only gives you ONE datanode and judging by the rest of your code you want all the data nodes. So you have to do this:

XmlNodeList datanodes = doc.DocumentElement.SelectNodes("/project/data");

Now your foreach loop was correct, but you kept selecting datanode instead of the variable(dataVar) you're suppose to loop through.

XmlNode innerDataNode;
foreach (XmlNode dataVar in datanodes)
{
    innerDataNode = dataVar.SelectSingleNode("./subdata");
    Console.WriteLine(innerDataNode.InnerText);
}
like image 184
Kent Kostelac Avatar answered Feb 05 '26 20:02

Kent Kostelac