Is there a way to check if the node I am looking for, using XPATH
does contain subnodes or not?
I have an xml file that a specific node sometimes has childs and some time it does not! How to check for this so I dont get too much NullReferenceExceptions !?
Check the example below:
var text = xml.SelectSingleNode("/Document/Tests/Test").InnerText;
If the current xml file I am working with does have the Test
node inside Tests
its working ok, but in another xml file the Tests
node does not contain anything and it is just there for no apparent reason!?
Is there a command in XPATH to do this? something like!! :
"/Document/Tests[NodeExist(Test)]
/Document/Tests[Test]
will give you Tests
nodes that only have a Test
node as a child.
You can also run a selection against /Document/Tests
and later call element.GetElementsByTagName("Test").Count > 0
to make sure there is at least one Test
node. This way you can programmatically show an empty string or an error message without the exception.
Yes You can use the following xpath "/Document/Tests[node()]" This will give you all the Tests Nodes that have a child node. You can further improve to give the node name there as well as nodetype.
If you want specific nodes that have a child node called Test use this "/Document/Tests[Test]"
More examples you can find in MSDN http://msdn.microsoft.com/en-us/library/ms256086.aspx
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