1
2
3
4
5
6
7
8
9
10
11 package org.mule.module.xml.transformer;
12
13 import org.mule.api.transformer.TransformerException;
14 import org.mule.module.xml.util.XMLUtils;
15 import org.mule.transformer.AbstractTransformer;
16
17 import java.util.ArrayList;
18 import java.util.List;
19
20 import org.apache.commons.jxpath.JXPathContext;
21 import org.dom4j.Document;
22 import org.dom4j.Node;
23 import org.dom4j.XPath;
24
25
26
27
28
29
30
31
32
33 public class JXPathExtractor extends AbstractTransformer
34 {
35
36 private volatile String expression;
37
38 private volatile boolean singleResult = true;
39
40
41
42
43
44
45 public Object doTransform(Object src, String encoding) throws TransformerException
46 {
47 try
48 {
49 Object result;
50 Document doc = XMLUtils.toDocument(src);
51
52
53 if (doc != null)
54 {
55 if (singleResult)
56 {
57 result = doc.valueOf(expression);
58 }
59 else
60 {
61 XPath xpath = doc.createXPath(expression);
62
63
64 List obj = (List)xpath.evaluate(doc);
65 result = new ArrayList(obj.size());
66 for (int i = 0; i < obj.size(); i++)
67 {
68 final Node node = (Node)obj.get(i);
69 ((List)result).add(node.getText());
70 }
71 }
72 }
73
74 else
75 {
76 JXPathContext context = JXPathContext.newContext(src);
77 result = context.getValue(expression);
78 }
79 return result;
80 }
81 catch (Exception e)
82 {
83 throw new TransformerException(this, e);
84 }
85 }
86
87
88
89
90 public String getExpression()
91 {
92 return expression;
93 }
94
95
96
97
98 public void setExpression(String expression)
99 {
100 this.expression = expression;
101 }
102
103
104
105
106
107
108 public boolean isSingleResult()
109 {
110 return singleResult;
111 }
112
113
114
115
116
117
118
119 public void setSingleResult(boolean singleResult)
120 {
121 this.singleResult = singleResult;
122 }
123 }