48

I tried to search for nodes containing text 'Yahoo' under '/doc/story/content', it returns 'content' node, but I need exact text node that contains 'Yahoo' or it's parent

<doc>
    <story>
        <content id="201009281450332423">
            <ul>MSW NYNES NYPG1 DILMA</ul>
            <p> <k> Yahoo, made </k> it nice </p>
            <p>
               <author>-v-</author>
            </p>
        </content>
    </story>
</doc>

Xpath: "/doc/story/content[contains(., 'Yahoo')]"

2 Answers 2

60

Since you need all textNodes only which contain the text Yahoo, use the following XPath.

//text()[contains(., 'Yahoo')]

This should return you all the textNodes only which contains Yahoo (case-sensitive) in it.

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

2 Comments

What it the difference between this answer and @Jon's?
Case insensitive: //text()[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜÉÈÊÀÁÂÒÓÔÙÚÛÇÅÏÕÑŒ', 'abcdefghijklmnopqrstuvwxyzäöüéèêàáâòóôùúûçåïõñœ'),'yahoo')]
42

Your XML is malformed. </content></doc></story> should be </content></story></doc>.

Apart from that, the XPath you would want is

/doc/story/content//*[contains(., 'Yahoo')]

(select any descendant of <content> which contains the text "Yahoo" -- this will select the <p>)

7 Comments

This works great if it's one level down, How to make it work for multi-nested tags?
@Vjy: I 'm not sure what you mean. Can you give an example?
Updated the above xml with additional tag <K>, it should select K instead of P tag. this is just example, the text node can be n level deep.
@Vjy: this does exactly what you asked for.
text() is a node test not a string. contains() expects strings. See stackoverflow.com/a/9493870/695671 Your solution may appear to work, but I have a case with text nodes within text nodes in which case it fails.
|

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.