1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.xml;
17
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Collections;
21
22 import org.apache.commons.jelly.JellyTagException;
23 import org.apache.commons.jelly.XMLOutput;
24 import org.apache.commons.jelly.xpath.XPathComparator;
25 import org.apache.commons.jelly.xpath.XPathSource;
26 import org.apache.commons.jelly.xpath.XPathTagSupport;
27
28 import org.jaxen.XPath;
29 import org.jaxen.JaxenException;
30
31 /*** A tag which performs an iteration over the results of an XPath expression
32 *
33 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
34 * @version $Revision: 155420 $
35 */
36 public class ForEachTag extends XPathTagSupport implements XPathSource {
37
38 /*** Holds the XPath selector. */
39 private XPath select;
40
41 /*** Xpath comparator for sorting */
42 private XPathComparator xpCmp = null;
43
44 /*** If specified then the current item iterated through will be defined
45 * as the given variable name. */
46 private String var;
47
48 /*** The current iteration value */
49 private Object iterationValue;
50
51
52 public ForEachTag() {
53 }
54
55
56
57 public void doTag(XMLOutput output) throws JellyTagException {
58 if (select != null) {
59 List nodes = null;
60 try {
61 nodes = select.selectNodes( getXPathContext() );
62 }
63 catch (JaxenException e) {
64 throw new JellyTagException(e);
65 }
66
67
68 if (xpCmp != null && (xpCmp.getXpath() != null)) {
69 Collections.sort(nodes, xpCmp);
70 }
71
72 Iterator iter = nodes.iterator();
73 while (iter.hasNext()) {
74 iterationValue = iter.next();
75 if (var != null) {
76 context.setVariable(var, iterationValue);
77 }
78 invokeBody(output);
79 }
80 }
81 }
82
83
84
85
86 /***
87 * @return the current XPath iteration value
88 * so that any other XPath aware child tags to use
89 */
90 public Object getXPathSource() {
91 return iterationValue;
92 }
93
94
95
96 /*** Sets the XPath selection expression
97 */
98 public void setSelect(XPath select) {
99 this.select = select;
100 }
101
102 /*** Sets the variable name to export for the item being iterated over
103 */
104 public void setVar(String var) {
105 this.var = var;
106 }
107
108 /*** Sets the xpath expression to use to sort selected nodes.
109 */
110 public void setSort(XPath sortXPath) throws JaxenException {
111 if (xpCmp == null) xpCmp = new XPathComparator();
112 xpCmp.setXpath(sortXPath);
113 }
114
115 /***
116 * Set whether to sort ascending or descending.
117 */
118 public void setDescending(boolean descending) {
119 if (xpCmp == null) xpCmp = new XPathComparator();
120 xpCmp.setDescending(descending);
121 }
122
123
124
125
126 protected Object getXPathContext() {
127 return super.getXPathContext();
128 }
129
130 }