Ogawa
Ogawa

Reputation: 87

How to create nested conditions in XPath that refer to other nodes

In a nested condition, how do I refer to the current node in the "outer" pair of brackets. Say I have the following xml:

<?xml version="1.0" encoding="utf-8"?>
<Root>
    <Gizmos>
        <Gizmo>
            <Id>1</Id>
        </Gizmo>
        <Gizmo>
            <Id>2</Id>
        </Gizmo>
        <Gizmo>
            <Id>3</Id>
        </Gizmo>
    </Gizmos>
    <Validations>
        <Validation>
            <Id>A</Id>
            <GizmoId>1</GizmoId>
        </Validation>
        <Validation>
            <Id>B</Id>
            <GizmoId>2</GizmoId>
        </Validation>
        <Validation>
            <Id>C</Id>
            <GizmoId>3</GizmoId>
        </Validation>
    </Validations>
    <Approvals>
        <ValidationId>B</ValidationId>
        <ValidationId>C</ValidationId>
    </Approvals>
</Root>

I would like to use this code to filter out a nodeset of approved gizmos (i.e. gizmo 2 and 3):

/Root/Gizmos/Gizmo[/Root/Validations/Validation[GizmoId = ?.Id]/Id = /Root/Approvals/ValidationId]

Is this allowed, and if it is, what would I substitute the question mark with?

Upvotes: 2

Views: 2665

Answers (1)

harpo
harpo

Reputation: 43168

The following XPath returns Gizmo 2 and 3:

/Root/Gizmos/Gizmo[Id=/Root/Validations/Validation[Id=/Root/Approvals/ValidationId]/GizmoId]

To break this down a bit, the inner expression

/Root/Validations/Validation[Id=/Root/Approvals/ValidationId]

returns all validations whose Id is contained in an Approval, viz,

<Validation>
  <Id>B</Id>
  <GizmoId>2</GizmoId>
</Validation> 

<Validation>
  <Id>C</Id>
  <GizmoId>3</GizmoId>
</Validation> 

You can use that expression to filter the full Gizmo list, by matching Id against GizmoId in the sub-expression.

Upvotes: 4

Related Questions