Reputation: 663
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.
Upvotes: 4
Views: 6648
Reputation: 223073
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()])
Upvotes: 6
Reputation: 33153
This LINQ to XML query should get close to what you are after:
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 count of the query == 0 you have no elements with content.
Depending on what you are after and if you have no other uses for LINQ style manipulation, the xPath solution posted may well be a better fit.
Upvotes: 0