Home > front end >  Finding XML elements using xpath and conditions
Finding XML elements using xpath and conditions

Time:03-16

I have an XML document for which I need to extract some text, and I'm trying to define an xpath expression that would find that element based on the value of a ancestor/sibling node.

Easier with an example... In the XML below, for each <feature> node, I want to get the value of the <content> elements only if the textual value of the <name> element is "positive":

<root>
    <feature id="1c4">
        <head>
            <name>positive</name>
        </head>
        <values>
            <value id="qwqwq">
                <content>Content-yes</content>
            </value>
        </values>

    </feature>
    <feature id="1c5">
        <head>
            <name>negative</name>
        </head>
        <values>
            <value id="wtrwt">
                <content>Target-no</content>
            </value>
        </values>
    </feature>
</root>

I can easily find all the elements (including the ones I don't want) with this: //root/feature/values/value/content

And I can find the <name> elements if the content value is "positive": //root/feature/head/name[text() = "positive"]

But how can I combine both to find the values of //root/feature/values/value/content ONLY when //root/feature/head/name[text() = "positive"] is true?

I tried to combine the expressions at the <feature> node level, but that doesn't seem to be a valid xpath expression: //root/feature[/head/name[text() = "positive" and /values/value/content]

Thanks in advance for the help!

F

CodePudding user response:

Try this...

/root/feature[head/name='positive']/values/value/content
  • Related