p3lim
p3lim

Reputation: 2211

Cherry-picking with XPath

Given the following:

<xml>
    <cls>
        <cl id="foo">
            <a>1</a>
            <b>1</b>
        </cl>
        <cl id="bar">
            <a>4</a>
            <b>2</b>
        </cl>
        <cl id="foo">
            <a>1</a>
            <b>3</b>
        </cl>
    </cls>
    <orgs>
        <org clid="foo">
        </org>
        <org clid="foo">
        </org>
        <org clid="bar">
        </org>
        <org clid="bar">
        </org>
        <org clid="foo">
        </org>
    </orgs>
</xml>

How can I select the xml/orgs/orgs where org's clid matches one in xml/cls/cl (by its id attribute) where cl/a's value is 1?

It's a bit complex, and I don't see how I can deal with relations like that.

Compatibility with XPath 1.0 would be prefered.

Upvotes: 2

Views: 92

Answers (4)

Vitaliy Moskalyuk
Vitaliy Moskalyuk

Reputation: 2583

Try this: org where clid equal to id in cl that has a = 1 child

 //xml/orgs/org[@clid = //xml/cls/cl[a=1]/@id]

or if you don't want to keep xml, org and cls tags and make it shorter (but better keep original one if your xml is big/complex):

//org[@clid = //cl[a=1]/@id]

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185570

Try this (XPath 1.0 expression) :

xmllint --xpath '//orgs/org[@clid=string(//cls/cl/a[text()="1"]/ancestor::cl[1]/@id)]' file.xml

Output :

<org clid="foo">
</org><org clid="foo">
</org><org clid="foo">

Comments :

I fetch the id string dynamically

Upvotes: 0

kjhughes
kjhughes

Reputation: 111706

This XPath 1.0 expression,

//orgs/org[@clid=//cl[a=1]/@id]

will select all org elements with @clid attribute value equal to the @id attribute value of at least one cl element with a child a element with value of 1, as requested:

<org clid="foo">
        </org>
<org clid="foo">
        </org>
<org clid="foo">
        </org>

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

xpath expression:

//orgs/org[@clid=preceding::cls/cl[a=1]/@id]

Upvotes: 1

Related Questions