Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath selection of nodes that don't have a specific optional attribute

Tags:

xml

xpath

I need to get to the first node in this XML structure to make some changes:

<root-node>
    <child mandatory="val">
        ...
    </child>
    <child mandatory="val" optional1="opt1">
        ...
    </child>
    <child mandatory="val" optional1="opt2" optional2="opt3">
        ...
    </child>
</root-node>

Notice that all children have a mandatory attribute which has the same value in all cases, plus one or more optional attributes. But if I do an XPath on //root-node/child[@mandatory='val'] I'm worried I might get a reference to the other nodes as well, which I don't want to touch.

Is there any way to be more specific and exclude the nodes that have a certain attribute present in their structure?

like image 558
Andrei Suceava Avatar asked Mar 24 '23 13:03

Andrei Suceava


1 Answers

Following XPath will return child elements which have mandatory attribute equal to val and do not have optional1 attribute defined:

//child[@mandatory='val' and not(@optional1)]

If you need only first element, then just add [1] to expression:

root-node/child[@mandatory='val' and not(@optional1)][1]
like image 159
Sergey Berezovskiy Avatar answered Apr 25 '23 00:04

Sergey Berezovskiy