XPath: select child elements that do *not* have a specific name

43,429

Solution 1

/a/*[not(self::b)]

Solution 2

With XPath 2.0 you can even do

/a/(* except b)

Solution 3

Xpath will look:

a/*[name(.) !='b']

So, select children of 'a' whose name is not equal 'b'

Share:
43,429
Thomas
Author by

Thomas

Updated on July 08, 2022

Comments

  • Thomas
    Thomas almost 2 years
    <a>
       <b/>
       <c/>
       <d/>
       <b/>
       <e/>
    </a>
    

    How do I select those children of "a" that are not "b"?

  • AakashM
    AakashM over 14 years
    @Lucero: I owe @Tomalak for that idea :)
  • Sailaja
    Sailaja over 14 years
    When I run your XPath, I got only c,d,e nodes. But, node b is not included in it. How to get the node b also in the list excluding its children?
  • AakashM
    AakashM over 14 years
    @Sailaja : I think you should make your own separate question. When you do so, be sure to explain what you mean by getting node b but not its children - when xpath picks out a node, the node still has its children...
  • Lucero
    Lucero over 14 years
    This breaks when namespaces and prefixes are being used.
  • Dewfy
    Dewfy over 14 years
    @Lucero - according to source XML there is no namespace, but if so you have "local-name" function
  • Lucero
    Lucero over 14 years
    yeah, and local-name() breaks also because it will match elements from any namespace instead of a specific element name. Since samples posted here are often simplified (quite obvious here) I'd not be so sure that no namespaces will be used, and even then if someone googles and comes across this answer they should be aware that your solution does not work with namespaces.
  • Umair A.
    Umair A. over 11 years
    how about a child element with attribute?
  • AakashM
    AakashM over 11 years
    @UmairAshraf if you have a different question, you should Ask a new question