user2075124
user2075124

Reputation: 227

xpath: check if element is within other element

I have quite a large XML structure that in its simplest form looks kinda like this:

<document>
    <body>
        <section>
            <p>Some text</p>
        </section>
    </body>
    <backm>
        <section>
            <p>Some text</p>
            <figure><title>This</title></figure>
        </section>
    </backm>
</document>

The section levels can be almost limitless (both within the body and backm elements) so I can have a section in section in section in section, etc. and the figure element can be within a numlist, an itenmlist, a p, and a lot more elements.

What I want to do is to check if the title in figure element is somewhere within the backm element. Is this possible?

Upvotes: 1

Views: 193

Answers (1)

MattH
MattH

Reputation: 38247

A document could have multiple <backm> elements and it could have multiple <figure><title>Title</title></figure> elements in it. How you build your query depends on the situations you're trying to distinguish between.

//backm/descendant::figure/title

Will return the <title> elements that are the child of a <figure> element and the descendant of a <backm> element.

So:

count(//backm/descendant::figure/title) > 0

Will return True if there are 1 or more such title elements.


You can also express this using Double Negation

not(//backm[not(descendant::figure/title)])

I'm under the impression that this should have better performance.


//title[parent::figure][ancestor::backm]

Lists all <title> elements with a parent of <figure> and an <backm> ancestor.

Upvotes: 1

Related Questions