Get the non-empty element using XPATH

48,326

Solution 1

How about something like /root/group/p1[text() and not(../following-sibling::group/p1/text())]

In other words: get the p1 elements that have text and whose group parents are not followed by group nodes that have non-empty p1 elements.

Solution 2

This xpath should work as well:

//group/p1[string-length(text()) > 0] 

Solution 3

You may also use [not(node())] Selector. Example: //group/p1[not(node())]

Share:
48,326

Related videos on Youtube

Rowel
Author by

Rowel

Updated on July 02, 2020

Comments

  • Rowel
    Rowel about 4 years

    I have the following XML

    <?xml version = "1.0" encoding = "UTF-8"?>
    <root>
      <group>
        <p1></p1>
      </group>
      <group>
        <p1>value1</p1>
      </group>
      <group>
        <p1></p1>
      </group>
    </root>
    

    is it possible to get the last the node with value? in this case get the value of the second group/p1.

    • MikroDel
      MikroDel about 11 years
      Post your your xslt or xpath please
  • Marcus
    Marcus about 11 years
    I did, it returns one node as intended.
  • Rowel
    Rowel about 11 years
    this one works, i tried it here and it gives me what i want xpathtester.com/test
  • ovejaexiste
    ovejaexiste almost 10 years
    It also works with attributes like src //group/p1[string-length(@src) > 0]. Thanks!
  • chainstair
    chainstair over 4 years
    For me this worked, because I had texts with only one backspace inside: [string-length(text()) > 1] Thank you a lot @Nora :)
  • blisstdev
    blisstdev about 4 years
    Shouldn't this be the inverse of that? //group/p1[node()]
  • Digital Farmer
    Digital Farmer almost 3 years
    Amazing tip @Nora