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
21 import org.apache.commons.jelly.JellyTagException;
22 import org.apache.commons.jelly.MissingAttributeException;
23 import org.apache.commons.jelly.XMLOutput;
24 import org.apache.commons.jelly.xpath.XPathTagSupport;
25 import org.dom4j.Node;
26 import org.dom4j.io.SAXWriter;
27 import org.jaxen.JaxenException;
28 import org.jaxen.XPath;
29 import org.xml.sax.SAXException;
30
31 /*** A tag which performs a copy-of operation like the XSLT tag
32 *
33 * @author James Strachan
34 */
35 public class CopyOfTag extends XPathTagSupport {
36
37 /*** The XPath expression to evaluate. */
38 private XPath select;
39
40 /*** Should we output lexical XML data like comments
41 * or entity names?
42 */
43 private boolean lexical;
44
45 public CopyOfTag() {
46 }
47
48
49
50 public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
51 Object xpathContext = getXPathContext();
52
53 if (select == null) {
54 throw new MissingAttributeException( "select" );
55 }
56
57 SAXWriter saxWriter;
58
59 if (lexical) {
60 saxWriter = new SAXWriter(output, output);
61 } else {
62 saxWriter = new SAXWriter(output);
63 }
64
65 Object obj;
66 try {
67 obj = select.evaluate(xpathContext);
68 } catch (JaxenException e) {
69 throw new JellyTagException("Failed to evaluate XPath expression", e);
70 }
71
72 try {
73 if (obj instanceof List) {
74 List nodes = (List) obj;
75 for (Iterator iter = nodes.iterator(); iter.hasNext(); ) {
76 Object object = iter.next();
77 if ( object instanceof Node ) {
78 saxWriter.write( (Node) object );
79 }
80 else if (object != null ) {
81 saxWriter.write( object.toString() );
82 }
83 }
84 } else if (obj instanceof Node) {
85 saxWriter.write( (Node) obj );
86 } else {
87 saxWriter.write( obj.toString() );
88 }
89 } catch (SAXException e) {
90 throw new JellyTagException("Failed to write XML output.", e);
91 }
92 }
93
94
95
96 /*** Sets the XPath expression to evaluate. */
97 public void setSelect(XPath select) {
98 this.select = select;
99 }
100
101 public void setLexical(boolean lexical) {
102 this.lexical = lexical;
103 }
104 }