JSTL - using variables in an xpath?

2020-03-07 05:45发布

Here is what I would like to do:

<x:forEach var="node" select="$doc//*[name()='item']">
    <x:out select="*[name()='${nodeName}']" />
</x:forEach>

I want to select an XML node based on the variable nodeName.

The above code does not work. The only solution I can come up with goes like this:

<x:forEach var="node" select="$doc//*[name()='item']/*">
    <c:set var="nameTest"><x:out select="name($node)" /></c:set>
    <c:if test="${nameTest == nodeName}>
        <x:out select="$node" />
    </c:if>
</x:forEach>

Which is not an elegant solution and actually makes me kind of angry to look at.

Anyone have any better ideas please?

And for extra fun times I am stuck using JSTL 1.0

标签: xml jsp xslt jstl
2条回答
我只想做你的唯一
2楼-- · 2020-03-07 06:26

Found the answer:

Using JSTL Data as XPath Variables

Scoped variables can be used in XPath expressions ($implicitObject:variableName) similar to how they are used in EL (${implicitObject.variableName}). If the implicit object is omitted, scopes will be searched in standard order. Note that the “.” and “[]” notations cannot be used for accessing bean properties.

from the JSTL Quick Reference Sheet (pdf)

So my code becomes:

<x:set var="theNode" select="*[name()=$pageScope:nodeName]" />
<x:out select="$theNode" />
查看更多
The star\"
3楼-- · 2020-03-07 06:40

XSLT has parameters on its own, maybe that could help you. I've found an example here http://www.roseindia.net/jstl/param-xml-jstl-tag.shtml

I'll try to apply the concept to your example

...
<x:forEach select="$doc//*[name()='item']">
  <x:out select="*[name()='$nodeName']" />
</x:forEach>
...

And then when invoking:

<x:transform xml="your.xml" xslt="your.xsl">
  <x:param name="nodeName" value="${nodeName}" />
</x:transform>

I haven't tried it, I don't have the tools nearby. And I don't have your full code neither :)

Good luck.

查看更多
登录 后发表回答