Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a xml node contains sub child

Tags:

c#

xml

xpath

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)]

like image 784
Saeid Yazdani Avatar asked Aug 09 '12 10:08

Saeid Yazdani


2 Answers

/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.

like image 172
Sedat Kapanoglu Avatar answered Sep 30 '22 05:09

Sedat Kapanoglu


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

like image 41
Vamsi Mohan Jayanti Avatar answered Sep 30 '22 06:09

Vamsi Mohan Jayanti