Best method for checking empty child nodes in XML?

I have an xml that has a maximum of 3 levels. Now, using C # or Xpath, the best way to check if all child nodes in the parent node are empty.

Thanks at Advance.

+4
source share
2 answers

Based on a sample document:

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

This expression tells which children of foo/bar have children:

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

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

 foo/bar/*[text()] 

So that all children are empty (without children or text nodes), make sure that this expression returns true:

 not(foo/bar/*[count(*)>0 or text()]) 
+6
source

This LINQ to XML query should be close to what you are doing:

 XElement xml = new XElement("contacts", new XElement("contact", new XAttribute("contactId", ""), new XElement("firstName", ""), new XElement("lastName", ""), new XElement("Address", new XElement("Street", "")) ), 

new XElement("contact", new XAttribute("contactId", ""), new XElement("firstName", ""), new XElement("lastName", "") ) );

var query = from c in xml.Elements() where c.Value != "" select c;

Console.WriteLine(xml); Console.WriteLine(query.Count());

When the request counter == 0, you have no content items.

Depending on what you need, and if you don't have other uses for manipulating LINQ styles, the xPath solution posted may be better suited.

0
source

All Articles