Saturday, February 12, 2011

Best method to check the empty child nodes in XML?

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.

  • 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()])
    
    sebastian : man, i really need to digg into XPath... +1
    Chris Jester-Young : Thanks! Yes, XPath rocks. :-)
    HashName : 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.
    Chris Jester-Young : 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. :-)
    HashName : 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..
    Robert Rossney : Without XPath, XML would hardly be worth using.
  • 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.

    HashName : 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?
    From David Hall

0 comments:

Post a Comment