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.tagext.BodyTagSupport ; 24 import javax.servlet.jsp.JspException ; 25 26 import org.dom4j.Branch; 27 import org.dom4j.Document; 28 import org.dom4j.DocumentHelper; 29 import org.dom4j.DocumentException; 30 import org.dom4j.Element; 31 import org.dom4j.Node; 32 import org.dom4j.io.SAXReader; 33 34 import org.apache.taglibs.xtags.util.JspVariableContext; 35 36 41 public class ReplaceTag extends AbstractBodyTag { 42 43 public ReplaceTag() { 44 } 45 46 public int doEndTag() throws JspException { 47 Object context = TagHelper.getInputNodes(pageContext, this, false ); 48 if (context == null) { 49 logInfo( "No current node to replace" ); 50 return EVAL_PAGE; 51 } 52 53 try { 54 String xmlFragment = null; 55 if (bodyContent != null) { 56 xmlFragment = bodyContent.getString(); 57 } 58 if (context instanceof List ) { 59 List els = (List )context; 60 if (els.size() > 1) { 61 throw new JspException ( "Current context contains more than one node"); 62 } 63 if (els.size() == 1) { 64 context = els.get(0); 65 } 66 } 67 if (context instanceof Document) { 68 if (xmlFragment == null) { 69 throw new JspException ( "Cannot replace document with empty body"); 70 } 71 Document sourceDoc = (Document) context; 72 Document newDoc = DocumentHelper.parseText( xmlFragment ); 73 74 sourceDoc.clearContent(); 76 for ( int i = 0, size = newDoc.nodeCount(); i < size; i++ ) { 77 Node node = newDoc.node(i); 78 node.detach(); 80 sourceDoc.add( node ); 82 } 83 } else { 84 if (! (context instanceof Element) ) { 85 throw new JspException ( "Current node is not an Element: "+context.getClass().getName() ); 86 } 87 Element element = (Element)context; 88 89 SAXReader reader = new SAXReader(); 90 91 if (element.isRootElement()) { 92 if (xmlFragment == null) { 93 throw new JspException ( "Cannot replace root element with empty body"); 94 } 95 Document newDoc = DocumentHelper.parseText( xmlFragment ); 96 Document sourceDoc = element.getDocument(); 97 Element newRoot = newDoc.getRootElement(); 98 newRoot.detach(); 99 sourceDoc.setRootElement(newRoot); 100 } else { 101 Element parent = element.getParent(); 102 List parentContent = parent.content(); 103 int index = parentContent.indexOf(element); 104 parentContent.remove(index); 105 if (xmlFragment != null) { 106 Document newDoc = DocumentHelper.parseText( "<dummy>"+xmlFragment+"</dummy>" ); 107 parentContent.addAll(index, newDoc.getRootElement().content() ); 108 } 109 } 110 } 111 } catch (DocumentException e) { 112 handleException(e); 113 } 114 return EVAL_PAGE; 115 } 116 117 public void release() { 118 super.release(); 119 } 120 } 121 | Popular Tags |