1 16 17 package org.apache.taglibs.xtags.xpath; 18 19 import java.io.StringReader ; 20 import java.util.Iterator ; 21 import java.util.List ; 22 23 import javax.servlet.jsp.JspException ; 24 25 import org.dom4j.Document; 26 import org.dom4j.DocumentFactory; 27 import org.dom4j.DocumentException; 28 import org.dom4j.Element; 29 import org.dom4j.Node; 30 import org.dom4j.XPath; 31 import org.dom4j.io.SAXReader; 32 33 import org.apache.taglibs.xtags.util.JspVariableContext; 34 35 40 public class AddTag extends AbstractBodyTag { 41 42 private XPath beforeXPath; 43 private XPath afterXPath; 44 45 public AddTag() { 46 } 47 48 public int doEndTag() throws JspException { 49 Object element = TagHelper.getInputNodes(pageContext, this, false ); 50 if (element == null) { 51 throw new JspException ( "No current node to add content to" ); 52 } 53 if (! (element instanceof Element) ) { 54 throw new JspException ( "Current node is not an Element" ); 55 } 56 if (bodyContent != null) { 57 try { 58 StringReader sreader = new StringReader ("<dummy>"+bodyContent.getString()+"</dummy>"); 59 SAXReader reader = new SAXReader(); 60 Document doc = reader.read(sreader); 61 Element root = doc.getRootElement(); 62 List nodes = root.content(); 63 while (! nodes.isEmpty() ) { 64 Node node = (Node)nodes.remove(0); 65 node.detach(); 66 ((Element)element).add( node ); 67 } 68 } 69 catch (DocumentException e) { 70 handleException(e); 71 } 72 } 73 74 return EVAL_PAGE; 75 } 76 77 public void release() { 78 super.release(); 79 beforeXPath = null; 80 afterXPath = null; 81 } 82 83 84 87 91 public void setAfter(String after) { 92 this.afterXPath = createXPath( after ); 93 } 94 95 99 public void setBefore(String before) { 100 this.beforeXPath = createXPath( before ); 101 } 102 103 104 protected XPath createXPath(String xpathExpression) { 105 XPath xpath = getDocumentFactory().createXPath( xpathExpression ); 106 xpath.setVariableContext( JspVariableContext.getInstance( pageContext ) ); 107 return xpath; 108 } 109 110 111 protected DocumentFactory getDocumentFactory() { 112 return DocumentFactory.getInstance(); 113 } 114 } 115 | Popular Tags |