Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xPath: Select parent element only if child element doesn't contain a certain value

Given this:

<element_1> 
    <element_2>Text</element_2> 
    <element_3> 
        <element_4> 
            <element_5>Text with @ in Value</element_5> 
        </element_4> 
        <element_4> 
            <element_5>Test Text</element_5> 
        </element_4> 
    </element_3> 
    <element_6> 
        <element_7> 
            <element_8>0</element_8> 
...

How do I select all instances of element_1 that do not contain an '@' in element_5?

like image 729
Snekse Avatar asked Oct 01 '10 20:10

Snekse


2 Answers

How do I select all instances of element_1 that do not contain an '@' in element_5?

Use:

//element_1[not(.//element_5[contains(.,'@')])]

In English, this means: Select all "element_1" elements in the document that do not have an "element_5" descendant whose string value contains the string '@'.

I am using the // abbreviation only because the structure of the XML file isn't clear.

I always recommend to avoid using the // abbreviation always when this is possible, because otherwise this may result in very inefficient XPath evaluation.

like image 81
Dimitre Novatchev Avatar answered Oct 16 '22 06:10

Dimitre Novatchev


My XPath is a bit rusty, but something like this:

//element_1[.//element_5[not(contains(., "@"))]]
like image 39
dty Avatar answered Oct 16 '22 04:10

dty