Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath query for node names matching a certain pattern

Tags:

xpath

Is there a way to apply XPath's starts-with function to a node's name instead of its value? I want to select the FOObar and FOObaz nodes from the following XML document without selecting the notFOO node:

<?xml version="1.0" encoding="UTF-8" ?>
<RootNode>
    <FOObar xmlns="http://sample.example.com">
        <value>numOne</value>
    </FOObar>
    <FOObaz xmlns="http://sample.example.com">
        <value>numTwo</value>
    </FOObaz>
    <notFOO xmlns="http://sample.example.com">
        <value>numThree</value>
    </notFOO>
</RootNode>

I get that it's possible to use starts-with to search based on text nodes, e.g.

//sample:value[starts-with(.,'num')]

Is there a way to write the following that is syntactically valid?

//sample:[starts-with(node(),'FOO')]

This question originally came with an SSCCE, but now that the question is answered, all that code is just clutter. It's still available in the revision history, of course.

like image 459
Pops Avatar asked Feb 06 '12 21:02

Pops


1 Answers

Use the name() or local-name() functions to refer to nodes by name:

//*[starts-with(local-name(), 'FOO')]
like image 92
Wayne Avatar answered Oct 03 '22 23:10

Wayne