Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basics

Status
Not open for further replies.

Muddmuse

Programmer
Jul 31, 2001
85
US
What are square brackets used for in xpath? What is the difference between "nodename[@attribute]" and "nodename/@attribute"? When/why would you use one or the other?
 
The "nodename/@attribute" syntax is known as the axis, which is like a directory structure. It allows us to specify a path of nodes to use within a given context. Context could be the root of an xml document, or any node below the root node.

The nodename[@attribute] syntax allows you to specify further criteria for the node to match - this is known as a predicate. We can specify values for nodes and surrounding values of that node, such as parents, children, attributes, text etc.

You would tend to use the former and the latter together, in order to find a particular (set of) node(s).

For example:
given

<nodeparent>
wombles!!
<nodename attrbute='blue'>
hi there
</nodename>
<nodename attribute='green'>
hello!!
</nodename>
</nodeparent>

nodeparent/nodename[@attribute = 'blue'] -> finds all the nodes called &quot;nodename&quot; under the &quot;nodeparent&quot; node with an attribute of &quot;blue&quot;.


//nodename/* -> all nodes underneath all nodes called &quot;nodename&quot;.

nodename[@attribute = 'green']/../@text -> selects the text of the parent of nodes called nodename with an attribute of green

nodename[@text] -> selects nodename nodes with text in them. (Same as nodename[@text != ''],

nodename/@text -> selects the node even if it has no text.

and now a really complicated one, just to show you how good this xpath thingy is...!

//nodename[local-name(..) == &quot;nodeparent&quot;] -> would find all nodes called &quot;nodename&quot; in the entire document with a parent (&quot;..&quot;) that has the local-name of &quot;nodeparent&quot;. (The local-name function is used to find the actual node's name -- in our example, &quot;nodeparent&quot; -- instead of its content).


Exercise: If you put these into an xsl template that just printed out the values of the nodes, try to guess what values you'd get from the xml document above.

hope that helped.

matt
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top