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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With