Xpath Predicates

Xpath has predicates. Predicates are, according to the W3schools, used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
Consider the following structure:

<shop>
	<car>
		<name>fusca</name>
		<color>blue</color>
		<price>5000</price>
	</car>
	<car>
		<name>captiva</name>
		<color>red</color>
		<price/>
	</car>
	<car>
		<name>veracruz</name>
		<color/>
		<price>150000</price>
	</car>
</shop>

Using predicates to select:

• Cars have price < 7,000.00

/shop/car[price < 7000]

Result:

	<car>
		<name>fusca</name>
		<color>blue</color>
		<price>5000</price>
	</car>

• Cars have color = red

/shop/car[color = ‘red’]
Result:

<car>
    <name>captiva</name>
    <color>red</color>
    <price/>
</car>

If you´d want to select all characteristics´s car, but those characteristics can´t be empty, what could you do?

You can do this:

/shop/car/*[text() != ”]

What does it freaking mean?

That means you want all child (characteristics) of the all car node (/shop/car/*[text() != ”]), but children´s restriction is those can´t be empty. To be able that restriction, we can use predicate text(). This predicate returns node´s content, in this case, node´s content of the all car´s child (/shop/car/*[text() != ”]) . After received content, it will compare with empty (/shop/car/*[text() != ”]).

Result will be just one node:


<car>
	<name>fusca</name>
	<color>blue</color>
	<price>5000</price>
</car>

That´s all folks, thank´s!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s