tags:

views:

1574

answers:

2

Hi, I have a xml which is max 3 levels deep. Now by using C# or Xpath what the best method to check the whether all the child nodes under a parent node are empty.

Thanks in Advance.

+5  A: 

Given a sample document of:

<foo>
  <bar>
    <baz/>
    <baz>Hello, world!</baz>
    <baz><qux/></baz>
  </bar>
</foo>

This expression tells you which children of foo/bar have any child elements:

foo/bar/*[count(*)>0]

This expression tells you which children of foo/bar have any child text nodes:

foo/bar/*[text()]

So to ensure that all children are empty (no child elements or text nodes), ensure that this expression returns true:

not(foo/bar/*[count(*)>0 or text()])
Chris Jester-Young
man, i really need to digg into XPath... +1
sebastian
Thanks! Yes, XPath rocks. :-)
Chris Jester-Young
Thanks Chris, this looks nice and elegant. I more thing will it possible to exclude some child nodes as part of the check.For e.g, there are some nodes which i want to ignore whether they're filled or not.
HashName
Well, it depends on what you want to exclude, but in general, yes, you can. Feel free to edit your question to elaborate on what you'd like to exclude. :-)
Chris Jester-Young
Chris, you inspired me to learn more about XPath. Thanks to Zvon.org and Google now I understand the power of XPath. Amen!!!!Thanks again..
HashName
Without XPath, XML would hardly be worth using.
Robert Rossney
A: 
David Hall
Unfortunately I'm still in C# 2.0, so don't have the privilege of using LINQ. Will it be possible for you to suggest something else?
HashName