Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath > How can I select a node based on both its attributes and content?

Tags:

xml

xpath

Sample XML:

<assignments>
<assignment id="911990211" section-id="1942268885" item-count="21" sources="foo">
    <options>
        <value name="NumRetakes">4</value>
        <value name="MultipleResultGrading">6</value>
        <value name="MaxFeedbackAttempts">-1</value>
        <value name="ItemTakesBeforeHint">1</value>
        <value name="TimeAllowed">0</value>
    </options>
</assignment>
<assignment id="1425185257" section-id="1505958877" item-count="4" sources="bar">
    <options>
        <value name="NumRetakes">0</value>
        <value name="MultipleResultGrading">6</value>
        <value name="MaxFeedbackAttempts">3</value>
        <value name="ItemTakesBeforeHint">1</value>
        <value name="TimeAllowed">0</value>
    </options>
</assignment>
<assignments>

Using XPath, I would like to select all assignments/assignment/options/value nodes where the nodes "name" attribute is "MaxFeedbackAttempts" and the nodes content is "-1". That is to say, I want to return each node that looks like:

<value name="MaxFeedbackAttempts">-1</value>

I can get each assignments/assignment/options/value node with the specified attribute using:

//assignment/options/value[@name="MaxFeedbackAttempts"]

I am just not sure how to refine this path to also limit the results based on the nodes content. Is there any way to do this using XPath?

like image 833
Andrew Kirk Avatar asked Dec 22 '22 02:12

Andrew Kirk


2 Answers

//assignment/options/value[@name="MaxFeedbackAttempts" and text()="-1"]
like image 110
LaustN Avatar answered Jan 01 '23 10:01

LaustN


Use:

/assignments/assignment/options/value[@name='MaxFeedbackAttempts' and . = -1]

Try to avoid the // abbreviation as its evaluation can be very inefficient.

like image 43
Dimitre Novatchev Avatar answered Jan 01 '23 11:01

Dimitre Novatchev