1 10 11 package org.mule.transformers.xml; 12 13 import java.util.ArrayList ; 14 import java.util.List ; 15 16 import org.apache.commons.jxpath.JXPathContext; 17 import org.dom4j.Document; 18 import org.dom4j.DocumentHelper; 19 import org.dom4j.Node; 20 import org.dom4j.XPath; 21 22 import org.mule.transformers.AbstractTransformer; 23 import org.mule.umo.transformer.TransformerException; 24 25 33 public class JXPathExtractor extends AbstractTransformer 34 { 35 38 private static final long serialVersionUID = 8252278715641253900L; 39 40 private String expression; 41 42 private boolean singleResult = true; 43 44 49 public Object doTransform(Object src, String encoding) throws TransformerException 50 { 51 try 52 { 53 Object result; 54 if (src instanceof String ) 55 { 56 Document doc = DocumentHelper.parseText((String )src); 57 if (singleResult) 58 { 59 result = doc.valueOf(expression); 60 } 61 else 62 { 63 XPath xpath = doc.createXPath(expression); 64 List obj = (List )xpath.evaluate(doc); 67 result = new ArrayList (obj.size()); 68 for (int i = 0; i < obj.size(); i++) 69 { 70 final Node node = (Node)obj.get(i); 71 ((List )result).add(node.getText()); 72 } 73 } 74 } 75 else 76 { 77 JXPathContext context = JXPathContext.newContext(src); 78 result = context.getValue(expression); 79 } 80 return result; 81 } 82 catch (Exception e) 83 { 84 throw new TransformerException(this, e); 85 } 86 } 87 88 91 public String getExpression() 92 { 93 return expression; 94 } 95 96 99 public void setExpression(String expression) 100 { 101 this.expression = expression; 102 } 103 104 109 public boolean isSingleResult() 110 { 111 return singleResult; 112 } 113 114 120 public void setSingleResult(boolean singleResult) 121 { 122 this.singleResult = singleResult; 123 } 124 } 125 | Popular Tags |