1

I need to find a(only one) XML node which is having non-empty data. How to do this.

XML:

<root>
<tuple >
    <old>
        <a>
            <b></b>
        </a>
    </old>
</tuple>
<tuple >
    <old>
        <a>
            <b>http://google.com</b>
        </a>
    </old>
</tuple>
<tuple >
    <old>
        <a>
            <b>http://google.com</b>
        </a>
    </old>
</tuple>
</root>

XPATH I used:

/root/tuple/old/a/b[text() and not(//a/b/text())]

and

/root/tuple/old/a/b[string-length(text())>0]/text()

But for the above xpath expressions I am getting all the nodes which are non-empty, What I am doing wrong.

1
  • in this example all the elements except the first b are non-empty because they contain whitespace text nodes (the new lines and indentation). Commented Nov 27, 2013 at 9:21

2 Answers 2

4

You could use following XPath

/root/tuple/old/a/b[normalize-space(.) = ''][1]

I presume that whitespaces are not important for you (so I use normalize-space() function). The dot means actual element (i.e. <b>).

As you say you need just only one element so for the case there are more suitable elements I select only the first one ([1])

Sign up to request clarification or add additional context in comments.

1 Comment

You've got the test backwards - you're finding the empty b elements rather than the non-empty ones. And (when that's fixed) it will still give you two results (the second and third b elements) because they're both the first non-empty b in their respective parents. If you only want one result you need parentheses (/root/tuple/old/a/b[normalize-space()])[1]
0

You can use the following Xpath to check if the element has value.

boolean(/root/tuple[position()=2]/old/a/b[text() and string-length()>0])

The above path returns true if the element has text

Remove the boolean function to get the actual text as shown below.

/root/tuple[position()=2]/old/a/b[text() and string-length()>0]

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.