You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@xalan.apache.org by mu...@apache.org on 2026/02/14 06:10:05 UTC

(xalan-java) branch xalan-j_xslt3.0_mvn updated: commmitting xalan-j xslt 3.0 implementation improvements

This is an automated email from the ASF dual-hosted git repository.

mukulg pushed a commit to branch xalan-j_xslt3.0_mvn
in repository https://gitbox.apache.org/repos/asf/xalan-java.git


The following commit(s) were added to refs/heads/xalan-j_xslt3.0_mvn by this push:
     new 868ffe6f6 commmitting xalan-j xslt 3.0 implementation improvements
868ffe6f6 is described below

commit 868ffe6f6104a5d43c8e217f777203c3a2e7972c
Author: Mukul Gandhi <ga...@gmail.com>
AuthorDate: Sat Feb 14 11:39:37 2026 +0530

    commmitting xalan-j xslt 3.0 implementation improvements
---
 .../org/apache/xalan/processor/XSLTSchema.java     |   34 +-
 .../apache/xalan/templates/ElemAnalyzeString.java  |   42 +-
 .../apache/xalan/templates/ElemCallTemplate.java   |  245 +++--
 .../java/org/apache/xalan/templates/ElemCatch.java |   38 +-
 .../org/apache/xalan/templates/ElemChoose.java     |   41 +-
 .../org/apache/xalan/templates/ElemForEach.java    |    4 +-
 .../apache/xalan/templates/ElemForEachGroup.java   |    2 +-
 .../org/apache/xalan/templates/ElemFunction.java   |   27 +
 .../java/org/apache/xalan/templates/ElemIf.java    |   38 +-
 .../org/apache/xalan/templates/ElemIterate.java    |   43 +-
 .../xalan/templates/ElemMatchingSubstring.java     |   49 +-
 .../xalan/templates/ElemNonMatchingSubstring.java  |   49 +-
 .../org/apache/xalan/templates/ElemSequence.java   | 1055 ++++++++++----------
 .../org/apache/xalan/templates/ElemTemplate.java   |   27 +
 .../java/org/apache/xalan/templates/ElemTry.java   |   38 +-
 .../org/apache/xalan/templates/ElemUsePackage.java |   30 +-
 .../org/apache/xalan/templates/ElemValueOf.java    |   36 +
 .../org/apache/xalan/templates/ElemVariable.java   |   43 +-
 .../org/apache/xalan/templates/Stylesheet.java     |   14 +-
 .../apache/xalan/transformer/TransformerImpl.java  |  185 ++--
 .../xpath/functions/XSL3FunctionService.java       |   29 +-
 21 files changed, 1325 insertions(+), 744 deletions(-)

diff --git a/src/main/java/org/apache/xalan/processor/XSLTSchema.java b/src/main/java/org/apache/xalan/processor/XSLTSchema.java
index 9a873f5a6..6dbd3ae37 100644
--- a/src/main/java/org/apache/xalan/processor/XSLTSchema.java
+++ b/src/main/java/org/apache/xalan/processor/XSLTSchema.java
@@ -674,7 +674,7 @@ public class XSLTSchema extends XSLTElementDef
                                 		                  separatorAVTOpt,
                                                           disableOutputEscapingAttr,
                                                           xpathDefaultNamespaceAttrOpt,
-                                                          expandTextAttrOpt }, 
+                                                          expandTextAttrOpt, useWhenAttrOpt }, 
                                                new ProcessorTemplateElem(),
                                   ElemValueOf.class /* class object */, 20, true);        
     
@@ -844,7 +844,7 @@ public class XSLTSchema extends XSLTElementDef
 								             null /*alias */, templateElements,
 								             new XSLTAttributeDef[]{ selectAttrOpt, rollbackOutputAttrOpt, 
 								            		                 xpathDefaultNamespaceAttrOpt, 
-								            		                 expandTextAttrOpt, spaceAttr }, 
+								            		                 expandTextAttrOpt, useWhenAttrOpt, spaceAttr }, 
 								             new ProcessorTemplateElem(),
 								             ElemTry.class /* class object */, true, false, true, 20, true);
     
@@ -853,7 +853,7 @@ public class XSLTSchema extends XSLTElementDef
 								             null /*alias */, templateElements,
 								             new XSLTAttributeDef[]{ selectAttrOpt, errorsAttrOpt, 
 								            		                 xpathDefaultNamespaceAttrOpt, 
-								            		                 expandTextAttrOpt, spaceAttr }, 
+								            		                 expandTextAttrOpt, useWhenAttrOpt, spaceAttr }, 
 								             new ProcessorTemplateElem(),
 								             ElemCatch.class /* class object */, true, false, true, 20, true);
     
@@ -863,21 +863,23 @@ public class XSLTSchema extends XSLTElementDef
                                                 new XSLTAttributeDef[]{ regexAVTRequired, selectAttrRequired, 
                                                                         flagsAttrOpt, spaceAttr, 
                                                                         xpathDefaultNamespaceAttrOpt, 
-                                                                        expandTextAttrOpt }, 
+                                                                        expandTextAttrOpt, useWhenAttrOpt }, 
                                                 new ProcessorTemplateElem(),
                                                 ElemAnalyzeString.class /* class object */, true, false, true, 20, true);
     
     XSLTElementDef xslMatchingSubstring = new XSLTElementDef(this,
                                                 Constants.S_XSLNAMESPACEURL, "matching-substring",
                                                 null /*alias */, templateElements,
-                                                new XSLTAttributeDef[] { xpathDefaultNamespaceAttrOpt, expandTextAttrOpt }, 
+                                                new XSLTAttributeDef[] { xpathDefaultNamespaceAttrOpt, expandTextAttrOpt,
+                                                		                 useWhenAttrOpt }, 
                                                 new ProcessorTemplateElem(),
                                                 ElemMatchingSubstring.class /* class object */, true, false, true, 20, true);
     
     XSLTElementDef xslNonMatchingSubstring = new XSLTElementDef(this,
                                                 Constants.S_XSLNAMESPACEURL, "non-matching-substring",
                                                 null /*alias */, templateElements,
-                                                new XSLTAttributeDef[] { xpathDefaultNamespaceAttrOpt, expandTextAttrOpt }, 
+                                                new XSLTAttributeDef[] { xpathDefaultNamespaceAttrOpt, expandTextAttrOpt,
+                                                		                 useWhenAttrOpt }, 
                                                 new ProcessorTemplateElem(),
                                                 ElemNonMatchingSubstring.class /* class object */, true, false, true, 20, true);
     
@@ -885,7 +887,7 @@ public class XSLTSchema extends XSLTElementDef
                                                    null /*alias */, templateElementsAndParams,
                                                    new XSLTAttributeDef[]{ selectAttrRequired,
                                                 		                   xpathDefaultNamespaceAttrOpt, 
-                                                		                   expandTextAttrOpt }, new ProcessorTemplateElem(),
+                                                		                   expandTextAttrOpt, useWhenAttrOpt }, new ProcessorTemplateElem(),
                                                    ElemIterate.class /* class object */, true, false, true, 20, true);
     
     XSLTElementDef xslIterateOnCompletion = new XSLTElementDef(this, Constants.S_XSLNAMESPACEURL, "on-completion",
@@ -918,7 +920,7 @@ public class XSLTSchema extends XSLTElementDef
                                               templateElements /* elements */,  // %template;
                                               new XSLTAttributeDef[]{
                                                 testAttrRequired, xpathDefaultNamespaceAttrOpt,
-                                                expandTextAttrOpt, spaceAttr }, new ProcessorTemplateElem(),
+                                                expandTextAttrOpt, useWhenAttrOpt, spaceAttr }, new ProcessorTemplateElem(),
                                                              ElemIf.class /* class object */, 20, true);
     XSLTElementDef xslWhen =
       new XSLTElementDef(this, Constants.S_XSLNAMESPACEURL, "when",
@@ -941,7 +943,8 @@ public class XSLTSchema extends XSLTElementDef
                                  null /*alias */,
                                  new XSLTElementDef[]{ xslWhen,
                                                        xslOtherwise } /* elements */, 
-                                        new XSLTAttributeDef[]{ xpathDefaultNamespaceAttrOpt, expandTextAttrOpt, spaceAttr },
+                                        new XSLTAttributeDef[]{ xpathDefaultNamespaceAttrOpt, expandTextAttrOpt, 
+                                        		                useWhenAttrOpt, spaceAttr },
                                  new ProcessorTemplateElem(),
                                  ElemChoose.class /* class object */, true, false, true, 20, true);                                
     XSLTElementDef xslAttribute = new XSLTElementDef(this,
@@ -959,7 +962,7 @@ public class XSLTSchema extends XSLTElementDef
       new XSLTElementDef(this, Constants.S_XSLNAMESPACEURL, "call-template",
                          null /*alias */,
                          new XSLTElementDef[]{ xslWithParam } /* elements */,
-                         new XSLTAttributeDef[]{ nameAttrRequired },
+                         new XSLTAttributeDef[]{ nameAttrRequired, useWhenAttrOpt },
                          new ProcessorTemplateElem(),
                          ElemCallTemplate.class /* class object */, 20, true);
     XSLTElementDef xslVariable = new XSLTElementDef(this,
@@ -968,7 +971,7 @@ public class XSLTSchema extends XSLTElementDef
                                    templateElements /* elements */,  // %template;>
                                    new XSLTAttributeDef[]{ nameAttrRequired,
                                                            selectAttrOpt, asAttrOpt, xpathDefaultNamespaceAttrOpt, 
-                                                           expandTextAttrOpt }, 
+                                                           expandTextAttrOpt, useWhenAttrOpt }, 
                                   new ProcessorTemplateElem(),
                                    ElemVariable.class /* class object */, 20, true);
     XSLTElementDef xslSequence = new XSLTElementDef(this,
@@ -976,7 +979,7 @@ public class XSLTSchema extends XSLTElementDef
                                                  null /*alias */,
                                                  templateElements /* elements */,  // %template;>
                                                  new XSLTAttributeDef[]{ selectAttrOpt, xpathDefaultNamespaceAttrOpt,
-                                                		                 expandTextAttrOpt }, 
+                                                		                 expandTextAttrOpt, useWhenAttrOpt }, 
                                                  new ProcessorTemplateElem(),
                                                  ElemSequence.class /* class object */, 20, true);
     XSLTElementDef xslParam = new XSLTElementDef(this,
@@ -1396,7 +1399,7 @@ public class XSLTSchema extends XSLTElementDef
                                                    asAttrOpt,
                                                    visibilityAttrOpt,
                                                    xpathDefaultNamespaceAttrOpt,
-                                                   expandTextAttrOpt,
+                                                   expandTextAttrOpt, useWhenAttrOpt,
                                                    spaceAttr }, 
                                            new ProcessorTemplate(), ElemTemplate.class /* class object */, true, 20, true),
                                   
@@ -1410,7 +1413,7 @@ public class XSLTSchema extends XSLTElementDef
                                                   nameAttrRequired,
                                                   asAttrOpt, xpathDefaultNamespaceAttrOpt, expandTextAttrOpt, 
                                                   overrideAttrOpt, overrideExtFunctionAttrOpt, newEachTimeAttrOpt, 
-                                                  visibilityAttrOpt, cacheAttrOpt }, 
+                                                  visibilityAttrOpt, cacheAttrOpt, useWhenAttrOpt }, 
                                           new ProcessorTemplate(), ElemFunction.class /* class object */, true, 20, true),                                                                    
                                                                     
                                   new XSLTElementDef(
@@ -1419,7 +1422,8 @@ public class XSLTSchema extends XSLTElementDef
                                           "use-package",
                                           null /*alias */,
                                           new XSLTElementDef[] { acceptElemDef }, /* elements */
-                                          new XSLTAttributeDef[] { nameAttrUsePackageRequired, packageVersionAttrOpt }, 
+                                          new XSLTAttributeDef[] { nameAttrUsePackageRequired, packageVersionAttrOpt,
+                                        		                   useWhenAttrOpt }, 
                                           new ProcessorUsePackage(), ElemUsePackage.class /* class object */, true, 20, true),
                                   
                                   new XSLTElementDef(
diff --git a/src/main/java/org/apache/xalan/templates/ElemAnalyzeString.java b/src/main/java/org/apache/xalan/templates/ElemAnalyzeString.java
index 6edae7040..d18a414bd 100644
--- a/src/main/java/org/apache/xalan/templates/ElemAnalyzeString.java
+++ b/src/main/java/org/apache/xalan/templates/ElemAnalyzeString.java
@@ -193,6 +193,33 @@ public class ElemAnalyzeString extends ElemTemplateElement implements Expression
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * This function is called after everything else has been
@@ -249,7 +276,20 @@ public class ElemAnalyzeString extends ElemTemplateElement implements Expression
    * @throws TransformerException
    */
   public void execute(TransformerImpl transformer) throws TransformerException {
-      transformSelectedNodes(transformer);
+	  
+	  XPathContext xctxt = transformer.getXPathContext();
+
+	  final int sourceNode = xctxt.getCurrentNode();
+	    
+	  if (m_useWhen != null) {
+		 XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+		 if (xObj.bool()) {
+			transformSelectedNodes(transformer); 
+		 }
+	  }
+	  else {
+         transformSelectedNodes(transformer);
+	  }
   }
 
   /**
diff --git a/src/main/java/org/apache/xalan/templates/ElemCallTemplate.java b/src/main/java/org/apache/xalan/templates/ElemCallTemplate.java
index e84f27cea..ed7956b2d 100644
--- a/src/main/java/org/apache/xalan/templates/ElemCallTemplate.java
+++ b/src/main/java/org/apache/xalan/templates/ElemCallTemplate.java
@@ -15,9 +15,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id$
- */
 package org.apache.xalan.templates;
 
 import java.util.List;
@@ -31,18 +28,19 @@ import org.apache.xalan.transformer.TransformerImpl;
 import org.apache.xalan.xslt.util.XslTransformEvaluationHelper;
 import org.apache.xml.utils.QName;
 import org.apache.xpath.VariableStack;
+import org.apache.xpath.XPath;
 import org.apache.xpath.XPathContext;
 import org.apache.xpath.objects.XObject;
 import org.w3c.dom.DOMException;
 
 /**
- * Implementation of XSLT xsl:call-template element.
+ * Implementation of XSLT 3.0 instruction xsl:call-template.
  * 
  * @xsl.usage advanced
  */
 public class ElemCallTemplate extends ElemForEach
 {
-    static final long serialVersionUID = 5009634612916030591L;
+  static final long serialVersionUID = 5009634612916030591L;
 
   /**
    * An xsl:call-template element invokes a template by name;
@@ -146,6 +144,33 @@ public class ElemCallTemplate extends ElemForEach
 	  return m_expand_text_declared;
   }
   
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
+  
   /**
    * Used to implement XSLT tunnel parameters.
    */
@@ -256,108 +281,114 @@ public class ElemCallTemplate extends ElemForEach
    *
    * @throws TransformerException
    */
-  public void execute(
-          TransformerImpl transformer)
-            throws TransformerException
-  {
-
-    if (transformer.getDebug())
-      transformer.getTraceManager().emitTraceEvent(this);
-
-    if (null != m_template)
-    {
-      XPathContext xctxt = transformer.getXPathContext();
-      VariableStack vars = xctxt.getVarStack();
-
-      int thisframe = vars.getStackFrame();
-      int nextFrame = vars.link(m_template.m_frameSize);
-      
-      // We have to clear the section of the stack frame that has params 
-      // so that the default param evaluation will work correctly.
-      if (m_template.m_inArgsSize > 0)
-      {
-        vars.clearLocalSlots(0, m_template.m_inArgsSize);
-      
-        if (null != m_paramElems)
-        {
-          int currentNode = xctxt.getCurrentNode();
-          vars.setStackFrame(thisframe);
-          int size = m_paramElems.length;
-          
-          int maxParamStackFrameIndex = -1;
-          
-          for (int i = 0; i < size; i++) 
-          {
-            ElemWithParam ewp = m_paramElems[i];
-            if (ewp.m_index >= 0)
-            {
-              if (transformer.getDebug())
-                transformer.getTraceManager().emitTraceEvent(ewp);
-              XObject obj = ewp.getValue(transformer, currentNode);
-              if (transformer.getDebug())
-                transformer.getTraceManager().emitTraceEndEvent(ewp);                            
-              
-              String tunnelStrVal = ewp.getTunnel();
-              obj.setTunnel(tunnelStrVal);
-              QName qName = ewp.getName();
-              obj.setQName(qName);
-              
-              // Note here that the index for ElemWithParam must have been 
-              // statically made relative to the xsl:template being called, 
-              // NOT this xsl:template.
-              vars.setLocalVariable(ewp.m_index, obj, nextFrame);
-              maxParamStackFrameIndex = ewp.m_index; 
-            }
-          }
-          
-          propagateTunnelParameters(vars, thisframe, nextFrame, maxParamStackFrameIndex);
-          
-          vars.setStackFrame(nextFrame);
-        }
-        else {
-            vars.setStackFrame(thisframe);            
-            int maxParamStackFrameIndex = -1;
-            
-            propagateTunnelParameters(vars, thisframe, nextFrame, maxParamStackFrameIndex);             
-            
-            vars.setStackFrame(nextFrame);
-         }
-      }
-      
-      SourceLocator savedLocator = xctxt.getSAXLocator();
-
-      try
-      {
-        xctxt.setSAXLocator(m_template);
-
-        // template.executeChildTemplates(transformer, sourceNode, mode, true);
-        transformer.pushElemTemplateElement(m_template);
-        m_template.execute(transformer);
-      }
-      finally
-      {
-        transformer.popElemTemplateElement();
-        xctxt.setSAXLocator(savedLocator);
-        // When we entered this function, the current 
-        // frame buffer (cfb) index in the variable stack may 
-        // have been manually set.  If we just call 
-        // unlink(), however, it will restore the cfb to the 
-        // previous link index from the link stack, rather than 
-        // the manually set cfb.  So, 
-        // the only safe solution is to restore it back 
-        // to the same position it was on entry, since we're 
-        // really not working in a stack context here. (Bug4218)
-        vars.unlink(thisframe);
-      }
-    }
-    else
-    {
-      transformer.getMsgMgr().error(this, XSLTErrorResources.ER_TEMPLATE_NOT_FOUND,
-                                    new Object[]{ m_templateName });  //"Could not find template named: '"+templateName+"'");
-    }
-    
-    if (transformer.getDebug())
-	  transformer.getTraceManager().emitTraceEndEvent(this); 
+  public void execute(TransformerImpl transformer) throws TransformerException {
+
+	  if (transformer.getDebug())
+		  transformer.getTraceManager().emitTraceEvent(this);
+
+	  XPathContext xctxt = transformer.getXPathContext();
+
+	  final int sourceNode = xctxt.getCurrentNode();
+
+	  if (m_useWhen != null) {
+		  XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+		  if (!xObj.bool()) {
+			  return; 
+		  }
+	  }
+
+	  if (m_template != null)
+	  {      
+		  VariableStack vars = xctxt.getVarStack();
+
+		  int thisframe = vars.getStackFrame();
+		  int nextFrame = vars.link(m_template.m_frameSize);
+
+		  // We have to clear the section of the stack frame that has params 
+		  // so that the default param evaluation will work correctly.
+		  if (m_template.m_inArgsSize > 0)
+		  {
+			  vars.clearLocalSlots(0, m_template.m_inArgsSize);
+
+			  if (null != m_paramElems)
+			  {          
+				  vars.setStackFrame(thisframe);
+				  int size = m_paramElems.length;
+
+				  int maxParamStackFrameIndex = -1;
+
+				  for (int i = 0; i < size; i++) 
+				  {
+					  ElemWithParam ewp = m_paramElems[i];
+					  if (ewp.m_index >= 0)
+					  {
+						  if (transformer.getDebug())
+							  transformer.getTraceManager().emitTraceEvent(ewp);
+						  XObject obj = ewp.getValue(transformer, sourceNode);
+						  if (transformer.getDebug())
+							  transformer.getTraceManager().emitTraceEndEvent(ewp);                            
+
+						  String tunnelStrVal = ewp.getTunnel();
+						  obj.setTunnel(tunnelStrVal);
+						  QName qName = ewp.getName();
+						  obj.setQName(qName);
+
+						  // Note here that the index for ElemWithParam must have been 
+						  // statically made relative to the xsl:template being called, 
+						  // NOT this xsl:template.
+						  vars.setLocalVariable(ewp.m_index, obj, nextFrame);
+						  maxParamStackFrameIndex = ewp.m_index; 
+					  }
+				  }
+
+				  propagateTunnelParameters(vars, thisframe, nextFrame, maxParamStackFrameIndex);
+
+				  vars.setStackFrame(nextFrame);
+			  }
+			  else {
+				  vars.setStackFrame(thisframe);            
+				  int maxParamStackFrameIndex = -1;
+
+				  propagateTunnelParameters(vars, thisframe, nextFrame, maxParamStackFrameIndex);             
+
+				  vars.setStackFrame(nextFrame);
+			  }
+		  }
+
+		  SourceLocator savedLocator = xctxt.getSAXLocator();
+
+		  try
+		  {
+			  xctxt.setSAXLocator(m_template);
+
+			  // template.executeChildTemplates(transformer, sourceNode, mode, true);
+			  transformer.pushElemTemplateElement(m_template);
+			  m_template.execute(transformer);
+		  }
+		  finally
+		  {
+			  transformer.popElemTemplateElement();
+			  xctxt.setSAXLocator(savedLocator);
+			  // When we entered this function, the current 
+			  // frame buffer (cfb) index in the variable stack may 
+			  // have been manually set.  If we just call 
+			  // unlink(), however, it will restore the cfb to the 
+			  // previous link index from the link stack, rather than 
+			  // the manually set cfb.  So, 
+			  // the only safe solution is to restore it back 
+			  // to the same position it was on entry, since we're 
+			  // really not working in a stack context here. (Bug4218)
+			  vars.unlink(thisframe);
+		  }
+	  }
+	  else
+	  {
+		  transformer.getMsgMgr().error(this, XSLTErrorResources.ER_TEMPLATE_NOT_FOUND,
+				  new Object[]{ m_templateName });  //"Could not find template named: '"+templateName+"'");
+	  }
+
+	  if (transformer.getDebug())
+		  transformer.getTraceManager().emitTraceEndEvent(this); 
 
   }
   
diff --git a/src/main/java/org/apache/xalan/templates/ElemCatch.java b/src/main/java/org/apache/xalan/templates/ElemCatch.java
index f5bdf76d7..2d28d3e78 100644
--- a/src/main/java/org/apache/xalan/templates/ElemCatch.java
+++ b/src/main/java/org/apache/xalan/templates/ElemCatch.java
@@ -160,6 +160,33 @@ public class ElemCatch extends ElemTemplateElement implements ExpressionOwner {
 		return m_expand_text_declared;
 	}
 	
+	/**
+	 * An XPath expression for 'use-when' attribute. 
+	 */
+	private XPath m_useWhen = null;
+
+	/**
+	 * Method definition, to set the value of XSL attribute 
+	 * "use-when".
+	 * 
+	 * @param xpath            XPath expression for attribute "use-when"
+	 */
+	public void setUseWhen(XPath xpath)
+	{
+		m_useWhen = xpath;  
+	}
+
+	/**
+	 * Method definition, to get the value of XSL attribute 
+	 * "use-when".
+	 * 
+	 * @return			XPath expression for attribute "use-when"
+	 */
+	public XPath getUseWhen()
+	{
+		return m_useWhen;
+	}
+	
 	/**
 	 * This class field is used during, XPath.fixupVariables(..) 
 	 * evaluation as performed within object of this class.  
@@ -243,7 +270,14 @@ public class ElemCatch extends ElemTemplateElement implements ExpressionOwner {
 	    
 	    SourceLocator srcLocator = xctxt.getSAXLocator();
 	    
-	    int contextNode = xctxt.getContextNode();
+	    final int sourceNode = xctxt.getContextNode();
+	    
+	    if (m_useWhen != null) {
+	    	XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+	    	if (!xObj.bool()) {
+	    		return; 
+	    	}
+	    }
 	    
 	    ElemTemplateElement parentElem = getParentElem();
 	    if (!(parentElem instanceof ElemTry)) {
@@ -268,7 +302,7 @@ public class ElemCatch extends ElemTemplateElement implements ExpressionOwner {
     		}
 
     		m_selectExpression.setIsConcreteExceptionProcessing(true);
-    		XObject xpathEvalResult = m_selectExpression.execute(xctxt, contextNode, xctxt.getNamespaceContext());
+    		XObject xpathEvalResult = m_selectExpression.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
     		
     		ResultSequence rSeq = new ResultSequence();
 			rSeq.add(xpathEvalResult);
diff --git a/src/main/java/org/apache/xalan/templates/ElemChoose.java b/src/main/java/org/apache/xalan/templates/ElemChoose.java
index c2a4d2344..8e5e78123 100644
--- a/src/main/java/org/apache/xalan/templates/ElemChoose.java
+++ b/src/main/java/org/apache/xalan/templates/ElemChoose.java
@@ -107,6 +107,33 @@ public class ElemChoose extends ElemTemplateElement
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * Get an int constant identifying the type of element.
@@ -150,6 +177,17 @@ public class ElemChoose extends ElemTemplateElement
       transformer.getTraceManager().emitTraceEvent(this);
 
     boolean found = false;
+    
+    XPathContext xctxt = transformer.getXPathContext();
+    
+    final int sourceNode = xctxt.getCurrentNode(); 
+    
+    if (m_useWhen != null) {
+    	XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+    	if (!xObj.bool()) {
+    		return; 
+    	}
+    }
 
     for (ElemTemplateElement childElem = getFirstChildElem();
             childElem != null; childElem = childElem.getNextSiblingElem())
@@ -163,14 +201,11 @@ public class ElemChoose extends ElemTemplateElement
         ElemWhen when = (ElemWhen) childElem;                
 
         // must be xsl:when
-        XPathContext xctxt = transformer.getXPathContext();
         SourceLocator srcLocator = xctxt.getSAXLocator(); 
         XPath whenTest = when.getTest();
         if (when.getXpathDefaultNamespace() != null) {
            whenTest = new XPath(whenTest.getPatternString(), srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
         }
-        
-        int sourceNode = xctxt.getCurrentNode();
 
         if (transformer.getDebug())
         {
diff --git a/src/main/java/org/apache/xalan/templates/ElemForEach.java b/src/main/java/org/apache/xalan/templates/ElemForEach.java
index f5b4699f2..03afedcc9 100644
--- a/src/main/java/org/apache/xalan/templates/ElemForEach.java
+++ b/src/main/java/org/apache/xalan/templates/ElemForEach.java
@@ -208,7 +208,7 @@ public class ElemForEach extends ElemTemplateElement implements ExpressionOwner
    * An XPath expression for 'use-when' attribute. 
    */
   private XPath m_useWhen = null;
-  
+
   /**
    * Method definition, to set the value of XSL attribute 
    * "use-when".
@@ -228,7 +228,7 @@ public class ElemForEach extends ElemTemplateElement implements ExpressionOwner
    */
   public XPath getUseWhen()
   {
-      return m_useWhen;
+	  return m_useWhen;
   }
   
   private Vector m_vars;
diff --git a/src/main/java/org/apache/xalan/templates/ElemForEachGroup.java b/src/main/java/org/apache/xalan/templates/ElemForEachGroup.java
index 7053f5bcd..b649c9ce6 100644
--- a/src/main/java/org/apache/xalan/templates/ElemForEachGroup.java
+++ b/src/main/java/org/apache/xalan/templates/ElemForEachGroup.java
@@ -399,7 +399,7 @@ public class ElemForEachGroup extends ElemTemplateElement
    */
   public XPath getUseWhen()
   {
-      return m_useWhen;
+	  return m_useWhen;
   }
 
   /**
diff --git a/src/main/java/org/apache/xalan/templates/ElemFunction.java b/src/main/java/org/apache/xalan/templates/ElemFunction.java
index 30fb4aa8d..821890c82 100644
--- a/src/main/java/org/apache/xalan/templates/ElemFunction.java
+++ b/src/main/java/org/apache/xalan/templates/ElemFunction.java
@@ -334,6 +334,33 @@ public class ElemFunction extends ElemTemplate
   public boolean getCache() {
 	  return m_cache;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * Get an integer representation of the element type.
diff --git a/src/main/java/org/apache/xalan/templates/ElemIf.java b/src/main/java/org/apache/xalan/templates/ElemIf.java
index 702a0d3db..8491cc30b 100644
--- a/src/main/java/org/apache/xalan/templates/ElemIf.java
+++ b/src/main/java/org/apache/xalan/templates/ElemIf.java
@@ -138,6 +138,33 @@ public class ElemIf extends ElemTemplateElement
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * This function is called after everything else has been
@@ -198,6 +225,13 @@ public class ElemIf extends ElemTemplateElement
     XPathContext xctxt = transformer.getXPathContext();
     int sourceNode = xctxt.getCurrentNode();
     
+    if (m_useWhen != null) {
+       XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+       if (!xObj.bool()) {
+    	  return; 
+       }
+    }
+    
     if (m_xpath_default_namespace != null) {
        m_test = new XPath(m_test.getPatternString(), xctxt.getSAXLocator(), xctxt.getNamespaceContext(), XPath.SELECT, null);
     }
@@ -229,10 +263,6 @@ public class ElemIf extends ElemTemplateElement
       //    transformer.getTraceManager().emitSelectedEvent(sourceNode, this,
       //            "endTest", m_test, test);
     }
-    /*else if (m_test.bool(xctxt, sourceNode, this))
-    {
-      transformer.executeChildTemplates(this, true);
-    }*/
     else {
         XObject xpath3ContextItem = xctxt.getXPath3ContextItem();        
         if (xpath3ContextItem != null) {
diff --git a/src/main/java/org/apache/xalan/templates/ElemIterate.java b/src/main/java/org/apache/xalan/templates/ElemIterate.java
index 3c3015555..651306bd8 100644
--- a/src/main/java/org/apache/xalan/templates/ElemIterate.java
+++ b/src/main/java/org/apache/xalan/templates/ElemIterate.java
@@ -180,6 +180,33 @@ public class ElemIterate extends ElemTemplateElement implements ExpressionOwner
    	     return m_expand_text_declared;
      }
      
+     /**
+      * An XPath expression for 'use-when' attribute. 
+      */
+     private XPath m_useWhen = null;
+
+     /**
+      * Method definition, to set the value of XSL attribute 
+      * "use-when".
+      * 
+      * @param xpath            XPath expression for attribute "use-when"
+      */
+     public void setUseWhen(XPath xpath)
+     {
+    	 m_useWhen = xpath;  
+     }
+
+     /**
+      * Method definition, to get the value of XSL attribute 
+      * "use-when".
+      * 
+      * @return			XPath expression for attribute "use-when"
+      */
+     public XPath getUseWhen()
+     {
+    	 return m_useWhen;
+     }
+     
      /**
      * This function is called after everything else has been recomposed, 
      * and allows the template to set remaining values that may be based 
@@ -239,8 +266,20 @@ public class ElemIterate extends ElemTemplateElement implements ExpressionOwner
         * @throws TransformerException
        */
        public void execute(TransformerImpl transformer) throws TransformerException
-       {
-           transformSelectedXdmItems(transformer);
+       {    	   
+    	   XPathContext xctxt = transformer.getXPathContext();
+    	   
+ 		   final int sourceNode = xctxt.getCurrentNode();
+ 		  
+    	   if (m_useWhen != null) {    		  
+    		  XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+    		  if (xObj.bool()) {
+    			 transformSelectedXdmItems(transformer);  
+    		  }
+    	   }
+    	   else {
+    	      transformSelectedXdmItems(transformer);
+    	   }
        }
        
        /**
diff --git a/src/main/java/org/apache/xalan/templates/ElemMatchingSubstring.java b/src/main/java/org/apache/xalan/templates/ElemMatchingSubstring.java
index 25f85fa53..0fdb03670 100644
--- a/src/main/java/org/apache/xalan/templates/ElemMatchingSubstring.java
+++ b/src/main/java/org/apache/xalan/templates/ElemMatchingSubstring.java
@@ -15,9 +15,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id$
- */
 package org.apache.xalan.templates;
 
 import java.util.HashMap;
@@ -30,10 +27,12 @@ import org.apache.xml.dtm.DTM;
 import org.apache.xml.dtm.DTMManager;
 import org.apache.xpath.Expression;
 import org.apache.xpath.ExpressionOwner;
+import org.apache.xpath.XPath;
 import org.apache.xpath.XPathContext;
+import org.apache.xpath.objects.XObject;
 
 /**
-  * Implementation of the XSLT 3.0 xsl:matching-substring instruction.
+  * Implementation of XSLT 3.0 instruction xsl:matching-substring.
   *    
   * @author Mukul Gandhi <mu...@apache.org>
   *   
@@ -124,6 +123,33 @@ public class ElemMatchingSubstring extends ElemTemplateElement implements Expres
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * This function is called after everything else has been
@@ -171,7 +197,20 @@ public class ElemMatchingSubstring extends ElemTemplateElement implements Expres
    * @throws TransformerException
    */
   public void execute(TransformerImpl transformer) throws TransformerException {
-      transformSelectedNodes(transformer);
+      
+	  XPathContext xctxt = transformer.getXPathContext();
+
+	  final int sourceNode = xctxt.getCurrentNode();
+	    
+	  if (m_useWhen != null) {
+		 XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+		 if (xObj.bool()) {
+			transformSelectedNodes(transformer); 
+		 }
+	  }
+	  else {
+         transformSelectedNodes(transformer);
+	  }
   }
 
   /**
diff --git a/src/main/java/org/apache/xalan/templates/ElemNonMatchingSubstring.java b/src/main/java/org/apache/xalan/templates/ElemNonMatchingSubstring.java
index 8b0167946..1bcb73fff 100644
--- a/src/main/java/org/apache/xalan/templates/ElemNonMatchingSubstring.java
+++ b/src/main/java/org/apache/xalan/templates/ElemNonMatchingSubstring.java
@@ -15,9 +15,6 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-/*
- * $Id$
- */
 package org.apache.xalan.templates;
 
 import javax.xml.transform.TransformerException;
@@ -27,10 +24,12 @@ import org.apache.xml.dtm.DTM;
 import org.apache.xml.dtm.DTMManager;
 import org.apache.xpath.Expression;
 import org.apache.xpath.ExpressionOwner;
+import org.apache.xpath.XPath;
 import org.apache.xpath.XPathContext;
+import org.apache.xpath.objects.XObject;
 
 /**
- * Implementation of the XSLT 3.0 non-matching-substring instruction.
+ * Implementation of the XSLT 3.0 instruction xsl:non-matching-substring.
  *    
  * @author Mukul Gandhi <mu...@apache.org>
  *   
@@ -111,6 +110,33 @@ public class ElemNonMatchingSubstring extends ElemTemplateElement implements Exp
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * This function is called after everything else has been
@@ -158,7 +184,20 @@ public class ElemNonMatchingSubstring extends ElemTemplateElement implements Exp
    * @throws TransformerException
    */
   public void execute(TransformerImpl transformer) throws TransformerException {
-      transformSelectedNodes(transformer);
+	  
+	  XPathContext xctxt = transformer.getXPathContext();
+
+	  final int sourceNode = xctxt.getCurrentNode();
+	    
+	  if (m_useWhen != null) {
+		 XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+		 if (xObj.bool()) {
+			transformSelectedNodes(transformer); 
+		 }
+	  }
+	  else {
+         transformSelectedNodes(transformer);
+	  }
   }
 
   /**
diff --git a/src/main/java/org/apache/xalan/templates/ElemSequence.java b/src/main/java/org/apache/xalan/templates/ElemSequence.java
index b396059e3..4827a9cd7 100644
--- a/src/main/java/org/apache/xalan/templates/ElemSequence.java
+++ b/src/main/java/org/apache/xalan/templates/ElemSequence.java
@@ -232,6 +232,33 @@ public class ElemSequence extends ElemTemplateElement
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * Get an integer representation of the element type.
@@ -259,294 +286,569 @@ public class ElemSequence extends ElemTemplateElement
    */
   public void execute(TransformerImpl transformer) throws TransformerException {
 
-      int sourceNode = transformer.getXPathContext().getCurrentNode();
-  
-      processXslSequence(transformer, sourceNode);       
+	  XPathContext xctxt = transformer.getXPathContext();
+	  
+	  final int sourceNode = xctxt.getCurrentNode();
+      
+      if (m_useWhen != null) {
+    	 XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+    	 if (xObj.bool()) {
+    		processXslSequence(transformer, sourceNode); 
+    	 }
+      }
+      else {
+         processXslSequence(transformer, sourceNode);
+      }
   }
-
+  
   /**
-   * This method, helps to evaluate an xsl:sequence instruction.
+   * Method definition, to emit contents of xsl:sequence instruction's 
+   * evaluation result, to XSL transformation result tree.
    * 
-   * @param transformer non-null reference to the the current transform-time state.
-   * @param sourceNode non-null reference to the current source node.
-   *
+   * @param xctxt							An XPathContext object instance 
+   * @param transformer						TransformerImpl object instance
+   * @param xdmObject					    An XObject object instance, representing 
+   *                                        result of evaluation of the xsl:sequence 
+   *                                        instruction.
    * @throws TransformerException
+   * @throws SAXException
    */
-  public void processXslSequence(TransformerImpl transformer, int sourceNode) 
-                                                                           throws TransformerException
-  {
-
-	  XObject result = null;
-
-	  XPathContext xctxt = transformer.getXPathContext();
-
-	  xctxt.pushCurrentNode(sourceNode);
-
-	  SourceLocator srcLocator = xctxt.getSAXLocator();
-
-	  Expression selectExpression = null;
+  public void emitXdmItemToXSLResultTree(XPathContext xctxt, TransformerImpl transformer, 
+		                                                    XObject xdmObject) throws TransformerException, SAXException {
 	  
-	  if (m_xpath_default_namespace != null) {
-		  m_selectPattern = new XPath(m_selectPattern.getPatternString(), xctxt.getSAXLocator(), xctxt.getNamespaceContext(), XPath.SELECT, null);
+	  if (xdmObject instanceof XPathInlineFunction) {
+		  XslTransformData.m_xpathInlineFunction = (XPathInlineFunction)xdmObject;   
+	  }
+	  else if (xdmObject instanceof XPathMap) {
+		  XslTransformData.m_xpathMap = (XPathMap)xdmObject;
 	  }
+	  else {
+		  SerializationHandler handler = transformer.getSerializationHandler();
 
-	  try {        
-		  if (m_selectPattern != null) {
-			  ElemTemplateElement xslSeqChildElem = getFirstChildElem();
-			  while (xslSeqChildElem != null) {
-				  if (!(xslSeqChildElem instanceof ElemFallback)) {
-					  throw new javax.xml.transform.TransformerException("XTSE3185 : An XSL 'sequence' element cannot "
-																								                + "have both \"select\" attribute, and child content "
-																								                + "other than XSL 'fallback' element(s).", srcLocator); 
+		  int xObjectType = xdmObject.getType();
+		  String strVal = null;
+
+		  switch (xObjectType) {           
+		  case XObject.CLASS_NODESET :          
+			  ElemCopyOf.copyOfActionOnNodeSet((XMLNodeCursorImpl)xdmObject, transformer, handler, xctxt);          
+			  break;
+		  case XObject.CLASS_RTREEFRAG :
+			  SerializerUtils.outputResultTreeFragment(handler, xdmObject, xctxt);
+			  break;
+		  case XObject.CLASS_RESULT_SEQUENCE :         
+			  ResultSequence resultSequence = (ResultSequence)xdmObject;			  
+			  
+			  ElemTemplateElement elemTemplateParentElem = getParentElem();			  
+			  boolean isXslSeqDelimEmit = false;
+			  while (elemTemplateParentElem != null) {
+				  if (elemTemplateParentElem instanceof ElemCatch) {
+					  isXslSeqDelimEmit = true;
+					  
+					  break;
 				  }
 				  else {
-					  xslSeqChildElem = xslSeqChildElem.getNextSiblingElem(); 
+					  elemTemplateParentElem = elemTemplateParentElem.getParentElem(); 
 				  }
 			  }
-
-			  selectExpression = m_selectPattern.getExpression();
 			  
-			  if (selectExpression instanceof NodeTest) {
-				  NodeTest nodeTest = (NodeTest)selectExpression;
-				  XMLNodeCursorImpl xmlNodeCursorImpl = (XMLNodeCursorImpl)nodeTest.execute(xctxt);
-				  DTMCursorIterator iter = xmlNodeCursorImpl.iterRaw();
-				  if (iter.nextNode() == DTM.NULL) {					  
-					  if (!"".equals(nodeTest.getLocalName())) {
-						  ElemFunction elemFunction = XslTransformEvaluationHelper.getElemFunctionFromNodeTestExpression(nodeTest, transformer, srcLocator);
-						  if (elemFunction != null) {
-							  // Evaluation of xsl:sequence instruction resulted in a single 
-							  // xsl:function xdm function item. 
-							  XPathNamedFunctionReference xpathNamedFunctionReference = new XPathNamedFunctionReference();
-							  xpathNamedFunctionReference.setXslStylesheetFunction(elemFunction, getStylesheetRoot());
-							  xpathNamedFunctionReference.setArity(elemFunction.getArity());
-
-							  (XslTransformData.m_xpathNamedFunctionRefSequence).add(xpathNamedFunctionReference);
+			  if (isXslSeqDelimEmit) {
+				  ElemCopyOf.copyOfActionOnResultSequence(resultSequence, transformer, handler, xctxt, !isXslSeqDelimEmit, this);
+			  }
+			  else {
+				  elemTemplateParentElem = getParentElem();				  
+				  while (elemTemplateParentElem != null) {
+					  if ((elemTemplateParentElem instanceof ElemValueOf) || (elemTemplateParentElem instanceof ElemVariable)
+							                                              || (elemTemplateParentElem instanceof ElemFunction)) {
+						  isXslSeqDelimEmit = true;
 
-							  return;
-						  }
+						  break;
 					  }
+
+					  elemTemplateParentElem = elemTemplateParentElem.getParentElem();
 				  }
-				  else {
-					  // Reset the node reference
-					  xmlNodeCursorImpl.getFresh();
-				  }
+
+				  ElemCopyOf.copyOfActionOnResultSequence(resultSequence, transformer, handler, xctxt, isXslSeqDelimEmit, this);
 			  }
 			  
-			  if (selectExpression instanceof XPathSequenceConstructor) {
-				  // Handling the case, when XPath literal sequence constructor has all 
-				  // items as XPath 'named function reference' representing xsl:function.
-				  XPathSequenceConstructor xpathSequenceConstructor = (XPathSequenceConstructor)selectExpression;				  
-				  XObject xObjTemp = xpathSequenceConstructor.execute(xctxt);
-				  List<Boolean> boolList = new ArrayList<Boolean>();
-				  if (xObjTemp instanceof ResultSequence) {
-					 ResultSequence rSeq = (ResultSequence)xObjTemp;					 
-					 for (int idx = 0; idx < rSeq.size(); idx++) {
-						XObject xObj = rSeq.item(idx); 
-						if (xObj == null) {
-						   boolList.add(Boolean.valueOf(true));	
-						}
-					 }
-				  }
-				  
-				  if ((boolList.size() > 0) && (boolList.size() == ((ResultSequence)xObjTemp).size())) {
-					  List<String> seqConstructorXPathStrList = xpathSequenceConstructor.getSequenceConstructorXPathParts();
-					  for (int idx = 0; idx < seqConstructorXPathStrList.size(); idx++) {
-						  String xpathStr = seqConstructorXPathStrList.get(idx);
-						  XPath xpathObj = new XPath(xpathStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
-						  Expression xpathExpr = xpathObj.getExpression();
-						  if (xpathExpr instanceof NodeTest) {
-							  ElemFunction elemFunction = XslTransformEvaluationHelper.getElemFunctionFromNodeTestExpression(
-									                                                                                    (NodeTest)xpathExpr, transformer, srcLocator);
-							  if (elemFunction != null) {
-								  XPathNamedFunctionReference xpathNamedFunctionReference = new XPathNamedFunctionReference();
-								  xpathNamedFunctionReference.setXslStylesheetFunction(elemFunction, getStylesheetRoot());
-								  xpathNamedFunctionReference.setArity(elemFunction.getArity());
+			  break;
+		  default :
+			  // no op
+		  }
 
-								  (XslTransformData.m_xpathNamedFunctionRefSequence).add(xpathNamedFunctionReference);							 
-							  } 
-						  }
-						  else {
-							  break; 
-						  }
-					  }
+		  boolean isToAddStrValSerializationSuffix = isToAddXslSequenceSerializationSuffix(xctxt); 
 
-					  if ((XslTransformData.m_xpathNamedFunctionRefSequence).size() > 0) {
-						  return; 
-					  }
-			      }
-				  else if (xObjTemp instanceof ResultSequence) {
-					  ResultSequence rSeq = (ResultSequence)xObjTemp;
-					  boolList = new ArrayList<Boolean>();
-					  for (int idx = 0; idx < rSeq.size(); idx++) {
-						  XObject xObj = rSeq.item(idx);
-						  if (xObj instanceof XPathNamedFunctionReference) {
-							  boolList.add(Boolean.valueOf(true));
-						  }
-					  }
-					  
-					  if (boolList.size() == rSeq.size()) {
-						  for (int idx = 0; idx < rSeq.size(); idx++) {
-							  XObject xObj = rSeq.item(idx);
-							  (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)xObj);
-						  }
-					  }
-					  
-					  if ((XslTransformData.m_xpathNamedFunctionRefSequence).size() > 0) {
-						  return; 
-					  }
-				  }
+		  if ((xdmObject instanceof XBoolean) || (xdmObject instanceof XString)) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = xdmObject.str() + STRING_VAL_SER_SUFFIX;
 			  }
-			  else if (selectExpression instanceof XPathArrayConstructor) {
-				  XPathArrayConstructor xpathArrayCons = (XPathArrayConstructor)selectExpression;
-				  XslTransformData.m_xpathArray = (XPathArray)(xpathArrayCons.execute(xctxt));
-				  
-				  return;
+			  else {
+				  strVal = xdmObject.str();  
 			  }
 
-			  if (selectExpression instanceof XSL3ConstructorOrExtensionFunction) {
-				  XSL3ConstructorOrExtensionFunction xpathFunc = (XSL3ConstructorOrExtensionFunction)selectExpression;
-				  XSL3FunctionService xslFunctionService = xctxt.getXSLFunctionService();
-				  XObject evalResult = xslFunctionService.callFunction(xpathFunc, transformer, xctxt);
-				  if (evalResult != null) {
-					  result = evalResult;    
-				  }
-				  else {
-					  result = m_selectPattern.execute(xctxt, sourceNode, this);    
-				  }            
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XNumber) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = xdmObject.str() + STRING_VAL_SER_DOUBLE_SUFFIX;
 			  }
-			  else if ((selectExpression instanceof Function) || (selectExpression instanceof SimpleMapOperator) || 
-					                                             (selectExpression instanceof Range) ||
-					                                             (selectExpression instanceof XPathDynamicFunctionCall)) {
-				  result = m_selectPattern.execute(xctxt, sourceNode, this);
-				  if (result instanceof XPathArray) {
-					 XslTransformData.m_xpathArray = (XPathArray)result;
-					 
-					 return;
-				  }
-			  }			  
-			  else if (selectExpression instanceof Operation) {
-				  Operation xpathOperation = (Operation)selectExpression;            
-				  XObject leftOperand = (xpathOperation.getLeftOperand()).execute(xctxt);
-				  XObject rightOperand = (xpathOperation.getRightOperand()).execute(xctxt);
-				  result = xpathOperation.operate(leftOperand, rightOperand);
+			  else {
+				  strVal = xdmObject.str();  
 			  }
-			  else if (selectExpression instanceof SelfIteratorNoPredicate) {
-				  result = xctxt.getXPath3ContextItem();
+
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XSInteger) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = ((XSInteger)xdmObject).stringValue() + STRING_VAL_SER_INTEGER_SUFFIX;
+			  }
+			  else {
+				  strVal = ((XSInteger)xdmObject).stringValue();
 			  }
-			  else if (selectExpression instanceof LocPathIterator) {                        
-				  int contextNode = xctxt.getContextNode();
 
-				  LocPathIterator locPathIterator = (LocPathIterator)selectExpression;
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XSDecimal) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = ((XSDecimal)xdmObject).stringValue() + STRING_VAL_SER_DECIMAL_SUFFIX;
+			  }
+			  else {
+				  strVal = ((XSDecimal)xdmObject).stringValue();
+			  }
 
-				  DTMCursorIterator dtmIter = null;                     
-				  try {
-					  dtmIter = locPathIterator.asIterator(xctxt, contextNode);
-				  }
-				  catch (ClassCastException ex) {
-					  // no op
-				  }
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XSDouble) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = ((XSDouble)xdmObject).stringValue() + STRING_VAL_SER_DOUBLE_SUFFIX;
+			  }
+			  else {
+				  strVal = ((XSDouble)xdmObject).stringValue();
+			  }
 
-				  if (dtmIter != null) {               
-					  result = new XMLNodeCursorImpl(dtmIter);
-				  }
-				  else {
-					  ResultSequence resultSeq = new ResultSequence();
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XSFloat) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = ((XSFloat)xdmObject).stringValue() + STRING_VAL_SER_FLOAT_SUFFIX;
+			  }
+			  else {
+				  strVal = ((XSFloat)xdmObject).stringValue();
+			  }
 
-					  String xpathExprStr = m_selectPattern.getPatternString();
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+		  else if (xdmObject instanceof XSAnyAtomicType) {
+			  if (isToAddStrValSerializationSuffix) {
+				  strVal = ((XSAnyAtomicType)xdmObject).stringValue() + STRING_VAL_SER_SUFFIX;
+			  }
+			  else {
+				  strVal = ((XSAnyAtomicType)xdmObject).stringValue();
+			  }
 
-					  if (xpathExprStr.startsWith("$") && xpathExprStr.contains("[") && xpathExprStr.endsWith("]")) {
-						  ElemTemplateElement elemTemplateElement = (ElemTemplateElement)xctxt.getNamespaceContext();
-						  List<XMLNSDecl> prefixTable = null;
-						  if (elemTemplateElement != null) {
-							  prefixTable = (List<XMLNSDecl>)elemTemplateElement.getPrefixTable();
-						  }                                      
+			  handler.characters(strVal.toCharArray(), 0, strVal.length());
+		  }
+	  }
+  }
 
-						  String varRefXPathExprStr = "$" + xpathExprStr.substring(1, xpathExprStr.indexOf('['));
-						  String xpathIndexExprStr = xpathExprStr.substring(xpathExprStr.indexOf('[') + 1, 
-								  xpathExprStr.indexOf(']'));
+  /**
+   * This function is called after everything else has been
+   * recomposed, and allows the template to set remaining
+   * values that may be based on some other property that
+   * depends on recomposition.
+   */
+  public void compose(StylesheetRoot sroot) throws TransformerException {	  
+     StylesheetRoot.ComposeState cstate = sroot.getComposeState();
+    
+     java.util.Vector vnames = cstate.getVariableNames();
+        
+     m_vars = (Vector)vnames.clone();
+     m_globals_size = cstate.getGlobalsSize();
+        
+     if (m_selectPattern != null) {
+        m_selectPattern.fixupVariables(vnames, cstate.getGlobalsSize());
+     }
+    
+     super.compose(sroot);
+  }
+  
+  /**
+   * This after the template's children have been composed.
+   */
+  public void endCompose(StylesheetRoot sroot) throws TransformerException
+  {
+     super.endCompose(sroot);
+  }
+  
+  /**
+   * Set the parent as an ElemTemplateElement.
+   *
+   * @param p This node's parent as an ElemTemplateElement
+   */
+  public void setParentElem(ElemTemplateElement p)
+  {
+    super.setParentElem(p);
+  }
 
-						  // Evaluate the, variable reference XPath expression
-						  if (prefixTable != null) {
-							  varRefXPathExprStr = XslTransformEvaluationHelper.replaceNsUrisWithPrefixesOnXPathStr(varRefXPathExprStr, prefixTable);
-						  }                                      
+  
+  /**
+   * Call the children visitors.
+   * 
+   * @param visitor The visitor whose appropriate method will be called.
+   */
+  protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs)
+  {
+  	if (m_selectPattern != null) {
+  	   m_selectPattern.getExpression().callVisitors(m_selectPattern, visitor);
+  	}
+  	
+    super.callChildVisitors(visitor, callAttrs);
+  }
+  
+  /**
+   * Method definition, to check whether Xalan serialization suffix is 
+   * to be added when emitting xdm atomic values during evaluation of 
+   * xsl:sequence instruction.
+   */
+  public boolean isToAddXslSequenceSerializationSuffix(XPathContext xctxt) throws TransformerException {
+     
+     boolean result = true;
+     
+     ElemTemplateElement elemTemplateElem = getParentElem();
+     
+     String asAttrStrVal = null;
+     
+     while (elemTemplateElem != null) {
+        if (elemTemplateElem instanceof ElemFunction) {
+           asAttrStrVal = ((ElemFunction)elemTemplateElem).getAs();
+           
+           break;
+        }
+        else if (elemTemplateElem instanceof ElemVariable) {
+           asAttrStrVal = ((ElemVariable)elemTemplateElem).getAs();
+           
+           break;
+        }
+        else {
+           elemTemplateElem = elemTemplateElem.getParentElem();  
+        }
+     }
+     
+     if (asAttrStrVal != null) {
+         XPath seqTypeXPath = new XPath(asAttrStrVal, xctxt.getSAXLocator(), xctxt.getNamespaceContext(), 
+        		                                                             XPath.SELECT, null, true);
+         XObject seqTypeExpressionEvalResult = seqTypeXPath.execute(xctxt, xctxt.getContextNode(), 
+                                                                             xctxt.getNamespaceContext());
+         SequenceTypeData seqExpectedTypeData = (SequenceTypeData)seqTypeExpressionEvalResult;
+         if (seqExpectedTypeData.getSequenceTypeKindTest() != null) {
+            result = false; 
+         }
+     }
+     else {
+         result = false;
+     }
+     
+     return result; 
+  }
 
-						  XPath varXPathObj = new XPath(varRefXPathExprStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
-						  if (m_vars != null) {
-							  varXPathObj.fixupVariables(m_vars, m_globals_size);  
-						  }
+  public boolean getIsCalledFromXslFork() {
+	  return m_isCalledFromXslFork;
+  }
 
-						  XObject varEvalResult = varXPathObj.execute(xctxt, xctxt.getCurrentNode(), xctxt.getNamespaceContext());
+  public void setIsCalledFromXslFork(boolean isCalledFromXslFork) {
+	  this.m_isCalledFromXslFork = isCalledFromXslFork;
+  }
 
-						  // Evaluate the, xdm sequence index XPath expression
-						  if (prefixTable != null) {
-							  xpathIndexExprStr = XslTransformEvaluationHelper.replaceNsUrisWithPrefixesOnXPathStr(xpathIndexExprStr, prefixTable);
-						  }
+  public XObject getXslSequenceEvalResult() {
+	  return m_xslSequenceEvalResult;
+  }
 
-						  XPath xpathIndexObj = new XPath(xpathIndexExprStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
+  public void setXslSequenceEvalResult(XObject xslSequenceEvalResult) {
+	  this.m_xslSequenceEvalResult = xslSequenceEvalResult;
+  }
+  
+  /**
+   * Method definition, to evaluate an xsl:sequence instruction.
+   * 
+   * @param transformer non-null reference to the the current transform-time state.
+   * @param sourceNode non-null reference to the current source node.
+   *
+   * @throws TransformerException
+   */
+  private void processXslSequence(TransformerImpl transformer, int sourceNode) 
+                                                                           throws TransformerException
+  {
 
-						  if (m_vars != null) {
-							  xpathIndexObj.fixupVariables(m_vars, m_globals_size);  
-						  }
+	  XObject result = null;
 
-						  XObject seqIndexEvalResult = xpathIndexObj.execute(xctxt, xctxt.getCurrentNode(), xctxt.getNamespaceContext());
+	  XPathContext xctxt = transformer.getXPathContext();
 
-						  if (varEvalResult instanceof ResultSequence) {
-							  ResultSequence varEvalResultSeq = (ResultSequence)varEvalResult; 
+	  xctxt.pushCurrentNode(sourceNode);
 
-							  if (seqIndexEvalResult instanceof XNumber) {
-								  double dValIndex = ((XNumber)seqIndexEvalResult).num();
-								  if (dValIndex == (int)dValIndex) {
-									  XObject evalResult = varEvalResultSeq.item((int)dValIndex - 1);
-									  resultSeq.add(evalResult);
-								  }
-								  else {
-									  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
-									  		                                                                          + "sequence, is not an integer.", srcLocator); 
-								  }
-							  }
-							  else if (seqIndexEvalResult instanceof XSNumericType) {
-								  String indexStrVal = ((XSNumericType)seqIndexEvalResult).stringValue();
-								  double dValIndex = (Double.valueOf(indexStrVal)).doubleValue();
-								  if (dValIndex == (int)dValIndex) {
-									  XObject evalResult = varEvalResultSeq.item((int)dValIndex - 1);
-									  resultSeq.add(evalResult);
-								  }
-								  else {
-									  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
-                                                                                                                     + "sequence, is not an integer.", srcLocator);  
-								  }
-							  }
-							  else {
-								  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
-                                                                                                                    + "sequence, is not an integer.", srcLocator);   
-							  }
-						  }
-					  }
+	  SourceLocator srcLocator = xctxt.getSAXLocator();
 
-					  result = resultSeq;
-				  }
-			  }
+	  Expression selectExpression = null;
+	  
+	  if (m_xpath_default_namespace != null) {
+		  m_selectPattern = new XPath(m_selectPattern.getPatternString(), xctxt.getSAXLocator(), xctxt.getNamespaceContext(), XPath.SELECT, null);
+	  }
 
-			  if (result == null) {
-				  if (selectExpression instanceof XPathNamedFunctionReference) {
-					 (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)selectExpression); 
+	  try {        
+		  if (m_selectPattern != null) {
+			  ElemTemplateElement xslSeqChildElem = getFirstChildElem();
+			  while (xslSeqChildElem != null) {
+				  if (!(xslSeqChildElem instanceof ElemFallback)) {
+					  throw new javax.xml.transform.TransformerException("XTSE3185 : An XSL 'sequence' element cannot "
+																								                + "have both \"select\" attribute, and child content "
+																								                + "other than XSL 'fallback' element(s).", srcLocator); 
 				  }
 				  else {
-					  result = m_selectPattern.execute(xctxt, sourceNode, this);
-					  if (result instanceof XPathNamedFunctionReference) {
-						  (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)result);  
-					  }
-				  }				  				  
-			  }        
-		  }
-		  else if (getFirstChildElem() == null) {
-			  result = XString.EMPTYSTRING;
-		  }
-		  else {			  			    	 			  			  
-			  boolean isOnlyElemTextLiteral = false;
-			  boolean isOtherElem = false;
-			  for (ElemTemplateElement elem = getFirstChildElem(); elem != null; elem = elem.getNextSiblingElem()) {
-				  if ((elem instanceof ElemTextLiteral) && !isOtherElem) {
+					  xslSeqChildElem = xslSeqChildElem.getNextSiblingElem(); 
+				  }
+			  }
+
+			  selectExpression = m_selectPattern.getExpression();
+			  
+			  if (selectExpression instanceof NodeTest) {
+				  NodeTest nodeTest = (NodeTest)selectExpression;
+				  XMLNodeCursorImpl xmlNodeCursorImpl = (XMLNodeCursorImpl)nodeTest.execute(xctxt);
+				  DTMCursorIterator iter = xmlNodeCursorImpl.iterRaw();
+				  if (iter.nextNode() == DTM.NULL) {					  
+					  if (!"".equals(nodeTest.getLocalName())) {
+						  ElemFunction elemFunction = XslTransformEvaluationHelper.getElemFunctionFromNodeTestExpression(nodeTest, transformer, srcLocator);
+						  if (elemFunction != null) {
+							  // Evaluation of xsl:sequence instruction resulted in a single 
+							  // xsl:function xdm function item. 
+							  XPathNamedFunctionReference xpathNamedFunctionReference = new XPathNamedFunctionReference();
+							  xpathNamedFunctionReference.setXslStylesheetFunction(elemFunction, getStylesheetRoot());
+							  xpathNamedFunctionReference.setArity(elemFunction.getArity());
+
+							  (XslTransformData.m_xpathNamedFunctionRefSequence).add(xpathNamedFunctionReference);
+
+							  return;
+						  }
+					  }
+				  }
+				  else {
+					  // Reset the node reference
+					  xmlNodeCursorImpl.getFresh();
+				  }
+			  }
+			  
+			  if (selectExpression instanceof XPathSequenceConstructor) {
+				  // Handling the case, when XPath literal sequence constructor has all 
+				  // items as XPath 'named function reference' representing xsl:function.
+				  XPathSequenceConstructor xpathSequenceConstructor = (XPathSequenceConstructor)selectExpression;				  
+				  XObject xObjTemp = xpathSequenceConstructor.execute(xctxt);
+				  List<Boolean> boolList = new ArrayList<Boolean>();
+				  if (xObjTemp instanceof ResultSequence) {
+					 ResultSequence rSeq = (ResultSequence)xObjTemp;					 
+					 for (int idx = 0; idx < rSeq.size(); idx++) {
+						XObject xObj = rSeq.item(idx); 
+						if (xObj == null) {
+						   boolList.add(Boolean.valueOf(true));	
+						}
+					 }
+				  }
+				  
+				  if ((boolList.size() > 0) && (boolList.size() == ((ResultSequence)xObjTemp).size())) {
+					  List<String> seqConstructorXPathStrList = xpathSequenceConstructor.getSequenceConstructorXPathParts();
+					  for (int idx = 0; idx < seqConstructorXPathStrList.size(); idx++) {
+						  String xpathStr = seqConstructorXPathStrList.get(idx);
+						  XPath xpathObj = new XPath(xpathStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
+						  Expression xpathExpr = xpathObj.getExpression();
+						  if (xpathExpr instanceof NodeTest) {
+							  ElemFunction elemFunction = XslTransformEvaluationHelper.getElemFunctionFromNodeTestExpression(
+									                                                                                    (NodeTest)xpathExpr, transformer, srcLocator);
+							  if (elemFunction != null) {
+								  XPathNamedFunctionReference xpathNamedFunctionReference = new XPathNamedFunctionReference();
+								  xpathNamedFunctionReference.setXslStylesheetFunction(elemFunction, getStylesheetRoot());
+								  xpathNamedFunctionReference.setArity(elemFunction.getArity());
+
+								  (XslTransformData.m_xpathNamedFunctionRefSequence).add(xpathNamedFunctionReference);							 
+							  } 
+						  }
+						  else {
+							  break; 
+						  }
+					  }
+
+					  if ((XslTransformData.m_xpathNamedFunctionRefSequence).size() > 0) {
+						  return; 
+					  }
+			      }
+				  else if (xObjTemp instanceof ResultSequence) {
+					  ResultSequence rSeq = (ResultSequence)xObjTemp;
+					  boolList = new ArrayList<Boolean>();
+					  for (int idx = 0; idx < rSeq.size(); idx++) {
+						  XObject xObj = rSeq.item(idx);
+						  if (xObj instanceof XPathNamedFunctionReference) {
+							  boolList.add(Boolean.valueOf(true));
+						  }
+					  }
+					  
+					  if (boolList.size() == rSeq.size()) {
+						  for (int idx = 0; idx < rSeq.size(); idx++) {
+							  XObject xObj = rSeq.item(idx);
+							  (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)xObj);
+						  }
+					  }
+					  
+					  if ((XslTransformData.m_xpathNamedFunctionRefSequence).size() > 0) {
+						  return; 
+					  }
+				  }
+			  }
+			  else if (selectExpression instanceof XPathArrayConstructor) {
+				  XPathArrayConstructor xpathArrayCons = (XPathArrayConstructor)selectExpression;
+				  XslTransformData.m_xpathArray = (XPathArray)(xpathArrayCons.execute(xctxt));
+				  
+				  return;
+			  }
+
+			  if (selectExpression instanceof XSL3ConstructorOrExtensionFunction) {
+				  XSL3ConstructorOrExtensionFunction xpathFunc = (XSL3ConstructorOrExtensionFunction)selectExpression;
+				  XSL3FunctionService xslFunctionService = xctxt.getXSLFunctionService();
+				  XObject evalResult = xslFunctionService.callFunction(xpathFunc, transformer, xctxt);
+				  if (evalResult != null) {
+					  result = evalResult;    
+				  }
+				  else {
+					  result = m_selectPattern.execute(xctxt, sourceNode, this);    
+				  }            
+			  }
+			  else if ((selectExpression instanceof Function) || (selectExpression instanceof SimpleMapOperator) || 
+					                                             (selectExpression instanceof Range) ||
+					                                             (selectExpression instanceof XPathDynamicFunctionCall)) {
+				  result = m_selectPattern.execute(xctxt, sourceNode, this);
+				  if (result instanceof XPathArray) {
+					 XslTransformData.m_xpathArray = (XPathArray)result;
+					 
+					 return;
+				  }
+			  }			  
+			  else if (selectExpression instanceof Operation) {
+				  Operation xpathOperation = (Operation)selectExpression;            
+				  XObject leftOperand = (xpathOperation.getLeftOperand()).execute(xctxt);
+				  XObject rightOperand = (xpathOperation.getRightOperand()).execute(xctxt);
+				  result = xpathOperation.operate(leftOperand, rightOperand);
+			  }
+			  else if (selectExpression instanceof SelfIteratorNoPredicate) {
+				  result = xctxt.getXPath3ContextItem();
+			  }
+			  else if (selectExpression instanceof LocPathIterator) {                        
+				  int contextNode = xctxt.getContextNode();
+
+				  LocPathIterator locPathIterator = (LocPathIterator)selectExpression;
+
+				  DTMCursorIterator dtmIter = null;                     
+				  try {
+					  dtmIter = locPathIterator.asIterator(xctxt, contextNode);
+				  }
+				  catch (ClassCastException ex) {
+					  // no op
+				  }
+
+				  if (dtmIter != null) {               
+					  result = new XMLNodeCursorImpl(dtmIter);
+				  }
+				  else {
+					  ResultSequence resultSeq = new ResultSequence();
+
+					  String xpathExprStr = m_selectPattern.getPatternString();
+
+					  if (xpathExprStr.startsWith("$") && xpathExprStr.contains("[") && xpathExprStr.endsWith("]")) {
+						  ElemTemplateElement elemTemplateElement = (ElemTemplateElement)xctxt.getNamespaceContext();
+						  List<XMLNSDecl> prefixTable = null;
+						  if (elemTemplateElement != null) {
+							  prefixTable = (List<XMLNSDecl>)elemTemplateElement.getPrefixTable();
+						  }                                      
+
+						  String varRefXPathExprStr = "$" + xpathExprStr.substring(1, xpathExprStr.indexOf('['));
+						  String xpathIndexExprStr = xpathExprStr.substring(xpathExprStr.indexOf('[') + 1, 
+								  xpathExprStr.indexOf(']'));
+
+						  // Evaluate the, variable reference XPath expression
+						  if (prefixTable != null) {
+							  varRefXPathExprStr = XslTransformEvaluationHelper.replaceNsUrisWithPrefixesOnXPathStr(varRefXPathExprStr, prefixTable);
+						  }                                      
+
+						  XPath varXPathObj = new XPath(varRefXPathExprStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
+						  if (m_vars != null) {
+							  varXPathObj.fixupVariables(m_vars, m_globals_size);  
+						  }
+
+						  XObject varEvalResult = varXPathObj.execute(xctxt, xctxt.getCurrentNode(), xctxt.getNamespaceContext());
+
+						  // Evaluate the, xdm sequence index XPath expression
+						  if (prefixTable != null) {
+							  xpathIndexExprStr = XslTransformEvaluationHelper.replaceNsUrisWithPrefixesOnXPathStr(xpathIndexExprStr, prefixTable);
+						  }
+
+						  XPath xpathIndexObj = new XPath(xpathIndexExprStr, srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
+
+						  if (m_vars != null) {
+							  xpathIndexObj.fixupVariables(m_vars, m_globals_size);  
+						  }
+
+						  XObject seqIndexEvalResult = xpathIndexObj.execute(xctxt, xctxt.getCurrentNode(), xctxt.getNamespaceContext());
+
+						  if (varEvalResult instanceof ResultSequence) {
+							  ResultSequence varEvalResultSeq = (ResultSequence)varEvalResult; 
+
+							  if (seqIndexEvalResult instanceof XNumber) {
+								  double dValIndex = ((XNumber)seqIndexEvalResult).num();
+								  if (dValIndex == (int)dValIndex) {
+									  XObject evalResult = varEvalResultSeq.item((int)dValIndex - 1);
+									  resultSeq.add(evalResult);
+								  }
+								  else {
+									  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
+									  		                                                                          + "sequence, is not an integer.", srcLocator); 
+								  }
+							  }
+							  else if (seqIndexEvalResult instanceof XSNumericType) {
+								  String indexStrVal = ((XSNumericType)seqIndexEvalResult).stringValue();
+								  double dValIndex = (Double.valueOf(indexStrVal)).doubleValue();
+								  if (dValIndex == (int)dValIndex) {
+									  XObject evalResult = varEvalResultSeq.item((int)dValIndex - 1);
+									  resultSeq.add(evalResult);
+								  }
+								  else {
+									  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
+                                                                                                                     + "sequence, is not an integer.", srcLocator);  
+								  }
+							  }
+							  else {
+								  throw new javax.xml.transform.TransformerException("XPTY0004 : An index reference used with an xdm "
+                                                                                                                    + "sequence, is not an integer.", srcLocator);   
+							  }
+						  }
+					  }
+
+					  result = resultSeq;
+				  }
+			  }
+
+			  if (result == null) {
+				  if (selectExpression instanceof XPathNamedFunctionReference) {
+					 (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)selectExpression); 
+				  }
+				  else {
+					  result = m_selectPattern.execute(xctxt, sourceNode, this);
+					  if (result instanceof XPathNamedFunctionReference) {
+						  (XslTransformData.m_xpathNamedFunctionRefSequence).add((XPathNamedFunctionReference)result);  
+					  }
+				  }				  				  
+			  }        
+		  }
+		  else if (getFirstChildElem() == null) {
+			  result = XString.EMPTYSTRING;
+		  }
+		  else {			  			    	 			  			  
+			  boolean isOnlyElemTextLiteral = false;
+			  boolean isOtherElem = false;
+			  for (ElemTemplateElement elem = getFirstChildElem(); elem != null; elem = elem.getNextSiblingElem()) {
+				  if ((elem instanceof ElemTextLiteral) && !isOtherElem) {
 					  isOnlyElemTextLiteral = true; 
 				  }
 				  else {
@@ -616,271 +918,6 @@ public class ElemSequence extends ElemTemplateElement
 	  finally {      
 		  xctxt.popCurrentNode();
 	  }   
-  }
-  
-  /**
-   * Method definition, to emit contents of xsl:sequence instruction's 
-   * evaluation result, to XSL transformation result tree.
-   * 
-   * @param xctxt							An XPathContext object instance 
-   * @param transformer						TransformerImpl object instance
-   * @param xdmObject					    An XObject object instance, representing 
-   *                                        result of evaluation of the xsl:sequence 
-   *                                        instruction.
-   * @throws TransformerException
-   * @throws SAXException
-   */
-  public void emitXdmItemToXSLResultTree(XPathContext xctxt, TransformerImpl transformer, 
-		                                                    XObject xdmObject) throws TransformerException, SAXException {
-	  
-	  if (xdmObject instanceof XPathInlineFunction) {
-		  XslTransformData.m_xpathInlineFunction = (XPathInlineFunction)xdmObject;   
-	  }
-	  else if (xdmObject instanceof XPathMap) {
-		  XslTransformData.m_xpathMap = (XPathMap)xdmObject;
-	  }
-	  else {
-		  SerializationHandler handler = transformer.getSerializationHandler();
-
-		  int xObjectType = xdmObject.getType();
-		  String strVal = null;
-
-		  switch (xObjectType) {           
-		  case XObject.CLASS_NODESET :          
-			  ElemCopyOf.copyOfActionOnNodeSet((XMLNodeCursorImpl)xdmObject, transformer, handler, xctxt);          
-			  break;
-		  case XObject.CLASS_RTREEFRAG :
-			  SerializerUtils.outputResultTreeFragment(handler, xdmObject, xctxt);
-			  break;
-		  case XObject.CLASS_RESULT_SEQUENCE :         
-			  ResultSequence resultSequence = (ResultSequence)xdmObject;			  
-			  
-			  ElemTemplateElement elemTemplateParentElem = getParentElem();			  
-			  boolean isXslSeqDelimEmit = false;
-			  while (elemTemplateParentElem != null) {
-				  if (elemTemplateParentElem instanceof ElemCatch) {
-					  isXslSeqDelimEmit = true;
-					  
-					  break;
-				  }
-				  else {
-					  elemTemplateParentElem = elemTemplateParentElem.getParentElem(); 
-				  }
-			  }
-			  
-			  if (isXslSeqDelimEmit) {
-				  ElemCopyOf.copyOfActionOnResultSequence(resultSequence, transformer, handler, xctxt, !isXslSeqDelimEmit, this);
-			  }
-			  else {
-				  elemTemplateParentElem = getParentElem();				  
-				  while (elemTemplateParentElem != null) {
-					  if ((elemTemplateParentElem instanceof ElemValueOf) || (elemTemplateParentElem instanceof ElemVariable)
-							                                              || (elemTemplateParentElem instanceof ElemFunction)) {
-						  isXslSeqDelimEmit = true;
-
-						  break;
-					  }
-
-					  elemTemplateParentElem = elemTemplateParentElem.getParentElem();
-				  }
-
-				  ElemCopyOf.copyOfActionOnResultSequence(resultSequence, transformer, handler, xctxt, isXslSeqDelimEmit, this);
-			  }
-			  
-			  break;
-		  default :
-			  // no op
-		  }
-
-		  boolean isToAddStrValSerializationSuffix = isToAddXslSequenceSerializationSuffix(xctxt); 
-
-		  if ((xdmObject instanceof XBoolean) || (xdmObject instanceof XString)) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = xdmObject.str() + STRING_VAL_SER_SUFFIX;
-			  }
-			  else {
-				  strVal = xdmObject.str();  
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XNumber) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = xdmObject.str() + STRING_VAL_SER_DOUBLE_SUFFIX;
-			  }
-			  else {
-				  strVal = xdmObject.str();  
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XSInteger) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = ((XSInteger)xdmObject).stringValue() + STRING_VAL_SER_INTEGER_SUFFIX;
-			  }
-			  else {
-				  strVal = ((XSInteger)xdmObject).stringValue();
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XSDecimal) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = ((XSDecimal)xdmObject).stringValue() + STRING_VAL_SER_DECIMAL_SUFFIX;
-			  }
-			  else {
-				  strVal = ((XSDecimal)xdmObject).stringValue();
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XSDouble) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = ((XSDouble)xdmObject).stringValue() + STRING_VAL_SER_DOUBLE_SUFFIX;
-			  }
-			  else {
-				  strVal = ((XSDouble)xdmObject).stringValue();
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XSFloat) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = ((XSFloat)xdmObject).stringValue() + STRING_VAL_SER_FLOAT_SUFFIX;
-			  }
-			  else {
-				  strVal = ((XSFloat)xdmObject).stringValue();
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-		  else if (xdmObject instanceof XSAnyAtomicType) {
-			  if (isToAddStrValSerializationSuffix) {
-				  strVal = ((XSAnyAtomicType)xdmObject).stringValue() + STRING_VAL_SER_SUFFIX;
-			  }
-			  else {
-				  strVal = ((XSAnyAtomicType)xdmObject).stringValue();
-			  }
-
-			  handler.characters(strVal.toCharArray(), 0, strVal.length());
-		  }
-	  }
-  }
-
-  /**
-   * This function is called after everything else has been
-   * recomposed, and allows the template to set remaining
-   * values that may be based on some other property that
-   * depends on recomposition.
-   */
-  public void compose(StylesheetRoot sroot) throws TransformerException {	  
-     StylesheetRoot.ComposeState cstate = sroot.getComposeState();
-    
-     java.util.Vector vnames = cstate.getVariableNames();
-        
-     m_vars = (Vector)vnames.clone();
-     m_globals_size = cstate.getGlobalsSize();
-        
-     if (m_selectPattern != null) {
-        m_selectPattern.fixupVariables(vnames, cstate.getGlobalsSize());
-     }
-    
-     super.compose(sroot);
-  }
-  
-  /**
-   * This after the template's children have been composed.
-   */
-  public void endCompose(StylesheetRoot sroot) throws TransformerException
-  {
-     super.endCompose(sroot);
-  }
-  
-  /**
-   * Set the parent as an ElemTemplateElement.
-   *
-   * @param p This node's parent as an ElemTemplateElement
-   */
-  public void setParentElem(ElemTemplateElement p)
-  {
-    super.setParentElem(p);
-  }
-
-  
-  /**
-   * Call the children visitors.
-   * 
-   * @param visitor The visitor whose appropriate method will be called.
-   */
-  protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs)
-  {
-  	if (m_selectPattern != null) {
-  	   m_selectPattern.getExpression().callVisitors(m_selectPattern, visitor);
-  	}
-  	
-    super.callChildVisitors(visitor, callAttrs);
-  }
-  
-  /**
-   * Method definition, to check whether Xalan serialization suffix is 
-   * to be added when emitting xdm atomic values during evaluation of 
-   * xsl:sequence instruction.
-   */
-  public boolean isToAddXslSequenceSerializationSuffix(XPathContext xctxt) throws TransformerException {
-     
-     boolean result = true;
-     
-     ElemTemplateElement elemTemplateElem = getParentElem();
-     
-     String asAttrStrVal = null;
-     
-     while (elemTemplateElem != null) {
-        if (elemTemplateElem instanceof ElemFunction) {
-           asAttrStrVal = ((ElemFunction)elemTemplateElem).getAs();
-           
-           break;
-        }
-        else if (elemTemplateElem instanceof ElemVariable) {
-           asAttrStrVal = ((ElemVariable)elemTemplateElem).getAs();
-           
-           break;
-        }
-        else {
-           elemTemplateElem = elemTemplateElem.getParentElem();  
-        }
-     }
-     
-     if (asAttrStrVal != null) {
-         XPath seqTypeXPath = new XPath(asAttrStrVal, xctxt.getSAXLocator(), xctxt.getNamespaceContext(), 
-        		                                                             XPath.SELECT, null, true);
-         XObject seqTypeExpressionEvalResult = seqTypeXPath.execute(xctxt, xctxt.getContextNode(), 
-                                                                             xctxt.getNamespaceContext());
-         SequenceTypeData seqExpectedTypeData = (SequenceTypeData)seqTypeExpressionEvalResult;
-         if (seqExpectedTypeData.getSequenceTypeKindTest() != null) {
-            result = false; 
-         }
-     }
-     else {
-         result = false;
-     }
-     
-     return result; 
-  }
-
-  public boolean getIsCalledFromXslFork() {
-	  return m_isCalledFromXslFork;
-  }
-
-  public void setIsCalledFromXslFork(boolean isCalledFromXslFork) {
-	  this.m_isCalledFromXslFork = isCalledFromXslFork;
-  }
-
-  public XObject getXslSequenceEvalResult() {
-	  return m_xslSequenceEvalResult;
-  }
-
-  public void setXslSequenceEvalResult(XObject xslSequenceEvalResult) {
-	  this.m_xslSequenceEvalResult = xslSequenceEvalResult;
-  }
+   }
 
 }
diff --git a/src/main/java/org/apache/xalan/templates/ElemTemplate.java b/src/main/java/org/apache/xalan/templates/ElemTemplate.java
index c8e4d790c..9a8f10353 100644
--- a/src/main/java/org/apache/xalan/templates/ElemTemplate.java
+++ b/src/main/java/org/apache/xalan/templates/ElemTemplate.java
@@ -385,6 +385,33 @@ public class ElemTemplate extends ElemTemplateElement
 	  return m_visibility;
   }
   
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
+  
   /**
    * Get an int constant identifying the type of element.
    * @see org.apache.xalan.templates.Constants
diff --git a/src/main/java/org/apache/xalan/templates/ElemTry.java b/src/main/java/org/apache/xalan/templates/ElemTry.java
index 237f18e4d..b84441d7b 100644
--- a/src/main/java/org/apache/xalan/templates/ElemTry.java
+++ b/src/main/java/org/apache/xalan/templates/ElemTry.java
@@ -169,6 +169,33 @@ public class ElemTry extends ElemTemplateElement implements ExpressionOwner {
 		return m_expand_text_declared;
 	}
 	
+	/**
+	 * An XPath expression for 'use-when' attribute. 
+	 */
+	private XPath m_useWhen = null;
+
+	/**
+	 * Method definition, to set the value of XSL attribute 
+	 * "use-when".
+	 * 
+	 * @param xpath            XPath expression for attribute "use-when"
+	 */
+	public void setUseWhen(XPath xpath)
+	{
+		m_useWhen = xpath;  
+	}
+
+	/**
+	 * Method definition, to get the value of XSL attribute 
+	 * "use-when".
+	 * 
+	 * @return			XPath expression for attribute "use-when"
+	 */
+	public XPath getUseWhen()
+	{
+		return m_useWhen;
+	}
+	
 	/**
 	 * This class field is used during, XPath.fixupVariables(..) 
 	 * evaluation as performed within object of this class.  
@@ -252,7 +279,14 @@ public class ElemTry extends ElemTemplateElement implements ExpressionOwner {
 	    
 	    SourceLocator srcLocator = xctxt.getSAXLocator();
 	    
-	    int contextNode = xctxt.getContextNode();
+	    final int sourceNode = xctxt.getContextNode();
+	    
+	    if (m_useWhen != null) {
+	    	XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+	    	if (!xObj.bool()) {
+	    		return; 
+	    	}
+	    }
 	    
 	    if ((m_selectExpression != null) && (m_xpath_default_namespace != null)) {    		
 	    	m_selectExpression = new XPath(m_selectExpression.getPatternString(), srcLocator, xctxt.getNamespaceContext(), XPath.SELECT, null);
@@ -291,7 +325,7 @@ public class ElemTry extends ElemTemplateElement implements ExpressionOwner {
 	    		}
 
 	    		m_selectExpression.setIsConcreteExceptionProcessing(true);
-	    		XObject xpathEvalResult = m_selectExpression.execute(xctxt, contextNode, xctxt.getNamespaceContext());
+	    		XObject xpathEvalResult = m_selectExpression.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
 	    		ResultSequence rSeq = new ResultSequence();
 	    		rSeq.add(xpathEvalResult);
 	    		SerializationHandler handler = transformer.getSerializationHandler(); 
diff --git a/src/main/java/org/apache/xalan/templates/ElemUsePackage.java b/src/main/java/org/apache/xalan/templates/ElemUsePackage.java
index 22730bb20..b73fc3e4a 100644
--- a/src/main/java/org/apache/xalan/templates/ElemUsePackage.java
+++ b/src/main/java/org/apache/xalan/templates/ElemUsePackage.java
@@ -21,10 +21,11 @@ import javax.xml.transform.SourceLocator;
 import javax.xml.transform.TransformerException;
 
 import org.apache.xalan.transformer.TransformerImpl;
+import org.apache.xpath.XPath;
 import org.apache.xpath.XPathContext;
 
 /**
- * Implementation of XSLT 3.0 xsl:use-package element.
+ * Implementation of XSLT 3.0 instruction xsl:use-package.
  * 
  * @author Mukul Gandhi <mu...@apache.org>
  * 
@@ -108,6 +109,33 @@ public class ElemUsePackage extends ElemTemplateElement
 	 return m_stylesheet; 
   }
   
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
+  
   /**
    * This function is called after everything else has been
    * recomposed, and allows the template to set remaining
diff --git a/src/main/java/org/apache/xalan/templates/ElemValueOf.java b/src/main/java/org/apache/xalan/templates/ElemValueOf.java
index 0d081c977..313630358 100644
--- a/src/main/java/org/apache/xalan/templates/ElemValueOf.java
+++ b/src/main/java/org/apache/xalan/templates/ElemValueOf.java
@@ -283,6 +283,33 @@ public class ElemValueOf extends ElemTemplateElement {
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * Get an integer representation of the element type.
@@ -353,6 +380,15 @@ public class ElemValueOf extends ElemTemplateElement {
     
     SourceLocator srcLocator = xctxt.getSAXLocator();
     
+    final int sourceNode = xctxt.getCurrentNode();
+    
+    if (m_useWhen != null) {
+       XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+       if (!xObj.bool()) {
+    	  return; 
+       }
+    }
+    
     SerializationHandler rth = transformer.getResultTreeHandler();
 
     if (transformer.getDebug())
diff --git a/src/main/java/org/apache/xalan/templates/ElemVariable.java b/src/main/java/org/apache/xalan/templates/ElemVariable.java
index 51ec21990..cd8e359d7 100644
--- a/src/main/java/org/apache/xalan/templates/ElemVariable.java
+++ b/src/main/java/org/apache/xalan/templates/ElemVariable.java
@@ -361,6 +361,33 @@ public class ElemVariable extends ElemTemplateElement
   public boolean getExpandTextDeclared() {
 	  return m_expand_text_declared;
   }
+  
+  /**
+   * An XPath expression for 'use-when' attribute. 
+   */
+  private XPath m_useWhen = null;
+
+  /**
+   * Method definition, to set the value of XSL attribute 
+   * "use-when".
+   * 
+   * @param xpath            XPath expression for attribute "use-when"
+   */
+  public void setUseWhen(XPath xpath)
+  {
+	  m_useWhen = xpath;  
+  }
+
+  /**
+   * Method definition, to get the value of XSL attribute 
+   * "use-when".
+   * 
+   * @return			XPath expression for attribute "use-when"
+   */
+  public XPath getUseWhen()
+  {
+	  return m_useWhen;
+  }
 
   /**
    * Get an integer representation of the element type.
@@ -415,8 +442,20 @@ public class ElemVariable extends ElemTemplateElement
     XPathContext xctxt = transformer.getXPathContext();
 
     final int sourceNode = xctxt.getCurrentNode();
-  
-    XObject var = getValue(transformer, sourceNode);
+    
+    XObject var = null;
+    if (m_useWhen != null) {
+       XObject xObj = m_useWhen.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+       if (xObj.bool()) {
+    	  var = getValue(transformer, sourceNode);  
+       }
+       else {
+    	  return; 
+       }
+    }
+    else {
+       var = getValue(transformer, sourceNode);
+    }
     
     if (var instanceof ResultSequence) {
     	ResultSequence rSeq = (ResultSequence)var;
diff --git a/src/main/java/org/apache/xalan/templates/Stylesheet.java b/src/main/java/org/apache/xalan/templates/Stylesheet.java
index 9171bc93c..3c1e1d443 100644
--- a/src/main/java/org/apache/xalan/templates/Stylesheet.java
+++ b/src/main/java/org/apache/xalan/templates/Stylesheet.java
@@ -1091,7 +1091,7 @@ public class Stylesheet extends ElemTemplateElement implements java.io.Serializa
 	/**
 	 * The "xsl:use-package" properties.
 	 */
-	private Vector m_usePackageVector;
+	private Vector m_usePackages;
 	
 	/**
 	 * The "xsl:expose" properties.
@@ -1136,16 +1136,16 @@ public class Stylesheet extends ElemTemplateElement implements java.io.Serializa
 	 *          reference objects.
 	 */
 	public void setUsePackage(ElemUsePackage v)
-	{
-		if (m_usePackageVector == null)
-			m_usePackageVector = new Vector();
+	{		
+		if (m_usePackages == null)
+			m_usePackages = new Vector();
 
-		m_usePackageVector.addElement(v);
+		m_usePackages.addElement(v);
 		v.setStylesheet(this);
 	}
 	
-	public Vector getUsePackageVector() {
-		return m_usePackageVector;
+	public Vector getUsePackages() {
+		return m_usePackages;
 	}
 	
 	/**
diff --git a/src/main/java/org/apache/xalan/transformer/TransformerImpl.java b/src/main/java/org/apache/xalan/transformer/TransformerImpl.java
index 60ae959d9..4538e9aab 100644
--- a/src/main/java/org/apache/xalan/transformer/TransformerImpl.java
+++ b/src/main/java/org/apache/xalan/transformer/TransformerImpl.java
@@ -162,8 +162,8 @@ import xml.xpath31.processor.types.XSString;
  * 
  * @xsl.usage advanced
  */
-public class TransformerImpl extends Transformer
-        implements Runnable, DTMWSFilter, ExtensionsProvider, org.apache.xml.serializer.SerializerTrace
+public class TransformerImpl extends Transformer implements Runnable, DTMWSFilter, ExtensionsProvider, 
+                                                                                                 org.apache.xml.serializer.SerializerTrace
 {
 
   // Synch object to gaurd against setting values from an 
@@ -1264,22 +1264,19 @@ public class TransformerImpl extends Transformer
           throws IllegalArgumentException
   {
 
-    synchronized (m_reentryGuard)
-    {
-
-      // Get the output format that was set by the user, otherwise get the 
-      // output format from the stylesheet.
-      if (null == m_outputFormat)
-      {
-        m_outputFormat =
-          (OutputProperties) getStylesheet().getOutputComposed().clone();
-      }
+    synchronized (m_reentryGuard) {
+    	// Get the output format that was set by the user, otherwise get the 
+    	// output format from the stylesheet.
+    	if (m_outputFormat == null)
+    	{
+    		m_outputFormat = (OutputProperties) getStylesheet().getOutputComposed().clone();
+    	}
 
-      if (!OutputProperties.isLegalPropertyKey(name))
-        throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
-                                           //+ name);
+    	if (!OutputProperties.isLegalPropertyKey(name))
+    		throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, new Object[]{name})); //"output property not recognized: "
+    	//+ name);
 
-      m_outputFormat.setProperty(name, value);
+    	m_outputFormat.setProperty(name, value);
     }
   }
 
@@ -1301,34 +1298,31 @@ public class TransformerImpl extends Transformer
    * @throws IllegalArgumentException if any of the argument keys are not
    * recognized and are not namespace qualified.   
    */
-  public void setOutputProperties(Properties oformat)
-  		throws IllegalArgumentException
+  public void setOutputProperties(Properties oformat) throws IllegalArgumentException
   {
 
-    synchronized (m_reentryGuard)
-    {
-      if (null != oformat)
-      {
-
-        // See if an *explicit* method was set.
-        String method = (String) oformat.get(OutputKeys.METHOD);
-
-        if (null != method)
-          m_outputFormat = new OutputProperties(method);
-        else if (m_outputFormat==null)
-          m_outputFormat = new OutputProperties();
-
-        m_outputFormat.copyFrom(oformat);
-        // copyFrom does not set properties that have been already set, so 
-        // this must be called after, which is a bit in the reverse from 
-        // what one might think.
-        m_outputFormat.copyFrom(m_stylesheetRoot.getOutputProperties());
-      }
-      else {
-        // if oformat is null JAXP says that any props previously set are removed
-        // and we are to revert back to those in the templates object (i.e. Stylesheet).
-        m_outputFormat = null;
-      }
+    synchronized (m_reentryGuard) {    	
+    	if (oformat != null)
+    	{
+    		// See if an *explicit* method was set
+    		String method = (String) oformat.get(OutputKeys.METHOD);
+
+    		if (null != method)
+    			m_outputFormat = new OutputProperties(method);
+    		else if (m_outputFormat==null)
+    			m_outputFormat = new OutputProperties();
+
+    		m_outputFormat.copyFrom(oformat);
+    		// copyFrom does not set properties that have been already set, so 
+    		// this must be called after, which is a bit in the reverse from 
+    		// what one might think.
+    		m_outputFormat.copyFrom(m_stylesheetRoot.getOutputProperties());
+    	}
+    	else {
+    		// if oformat is null JAXP says that any props previously set are removed
+    		// and we are to revert back to those in the templates object (i.e. Stylesheet).
+    		m_outputFormat = null;
+    	}
     }
   }
 
@@ -1574,12 +1568,12 @@ public class TransformerImpl extends Transformer
 	  
     synchronized (m_reentryGuard)
     {
-      SerializationHandler xoh = createSerializationHandler(outputTarget);
-      this.setSerializationHandler(xoh);        
+    	SerializationHandler xoh = createSerializationHandler(outputTarget);
+    	this.setSerializationHandler(xoh);        
 
-      m_outputTarget = outputTarget;
+    	m_outputTarget = outputTarget;
 
-      transform(xmlSource, shouldRelease);
+    	transform(xmlSource, shouldRelease);
     }
   }
 
@@ -2064,11 +2058,11 @@ public class TransformerImpl extends Transformer
 
     synchronized (m_reentryGuard)
     {
-      VariableStack varstack = new VariableStack();
+    	VariableStack varstack = new VariableStack();
 
-      m_xcontext.setVarStack(varstack);
+    	m_xcontext.setVarStack(varstack);
 
-      m_userParams = null;
+    	m_userParams = null;
     }
   }
 
@@ -2128,7 +2122,7 @@ public class TransformerImpl extends Transformer
 
     synchronized (m_reentryGuard)
     {
-      m_xcontext.getSourceTreeManager().setURIResolver(resolver);
+    	m_xcontext.getSourceTreeManager().setURIResolver(resolver);
     }
   }
 
@@ -2546,6 +2540,8 @@ public class TransformerImpl extends Transformer
         // Find the XSL template that is the best match for the 
         // element.        
         XPathContext xctxt = m_xcontext;
+        
+        final int sourceNode = xctxt.getCurrentNode();
 
         try
         {
@@ -2583,22 +2579,43 @@ public class TransformerImpl extends Transformer
                  m_xcontext.setSAXLocator(template);
            	     m_xcontext.getVarStack().link(template.m_frameSize);
            	     
-           	     if (XslTransformData.m_xsl_message_rSeq == null) {
-           	         // An XSL stylesheet doesn't contain xsl:message
-           		     // instruction.
-           	    	 executeChildTemplates(template, true);
+           	     XPath useWhenExpr = template.getUseWhen();
+           	     if (useWhenExpr != null) {
+           	    	 XObject xObj = useWhenExpr.execute(xctxt, sourceNode, xctxt.getNamespaceContext());           	    	 
+           	    	 if (xObj.bool()) {
+           	    		 if (XslTransformData.m_xsl_message_rSeq == null) {
+           	    			 // An XSL stylesheet doesn't contain xsl:message
+           	    			 // instruction.
+           	    			 executeChildTemplates(template, true);
+           	    		 }
+           	    		 else { 
+           	    			 // An XSL stylesheet contains one or more xsl:message
+           	    			 // instructions.
+           	    			 int rootNodeHandleOfRtf = this.transformToRTF(template);
+           	    			 NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, xctxt, template)).convertToNodeset();    	  
+           	    			 m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, xctxt);
+           	    		 } 
+           	    	 }
            	     }
-           	     else { 
-           	         // An XSL stylesheet contains one or more xsl:message
-           		     // instructions.
-           	    	 int rootNodeHandleOfRtf = this.transformToRTF(template);
-           	    	 NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, xctxt, template)).convertToNodeset();    	  
-           	    	 m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, xctxt);
+           	     else {
+           	    	 if (XslTransformData.m_xsl_message_rSeq == null) {
+           	    		 // An XSL stylesheet doesn't contain xsl:message
+           	    		 // instruction.
+           	    		 executeChildTemplates(template, true);
+           	    	 }
+           	    	 else { 
+           	    		 // An XSL stylesheet contains one or more xsl:message
+           	    		 // instructions.
+           	    		 int rootNodeHandleOfRtf = this.transformToRTF(template);
+           	    		 NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, xctxt, template)).convertToNodeset();    	  
+           	    		 m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, xctxt);
+           	    	 }
            	     }
-
+           	     
            	     if (m_debug)
            		    getTraceManager().emitTraceEndEvent(template);
            	     
+           	     
            	     return true;
              }
              else {
@@ -2749,17 +2766,39 @@ public class TransformerImpl extends Transformer
     	  m_xcontext.setSAXLocator(template);
     	  m_xcontext.getVarStack().link(template.m_frameSize);
     	  
-    	  if (XslTransformData.m_xsl_message_rSeq == null) {
-    		  // An XSL stylesheet doesn't contain xsl:message
-    		  // instruction.
-    		  executeChildTemplates(template, true);
+    	  final int sourceNode = m_xcontext.getCurrentNode();
+    	  
+    	  XPath useWhenExpr = template.getUseWhen();    	  
+    	  if (useWhenExpr != null) {
+    		  XObject xObj = useWhenExpr.execute(m_xcontext, sourceNode, m_xcontext.getNamespaceContext());    		  
+    		  if (xObj.bool()) {
+    			  if (XslTransformData.m_xsl_message_rSeq == null) {
+    				  // An XSL stylesheet doesn't contain xsl:message
+    				  // instruction.
+    				  executeChildTemplates(template, true);
+    			  }
+    			  else {
+    				  // An XSL stylesheet contains one or more xsl:message
+    				  // instructions.
+    				  int rootNodeHandleOfRtf = this.transformToRTF(template);
+    				  NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, m_xcontext, template)).convertToNodeset();    	  
+    				  m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, m_xcontext);
+    			  } 
+    		  }
     	  }
     	  else {
-    		  // An XSL stylesheet contains one or more xsl:message
-    		  // instructions.
-    		  int rootNodeHandleOfRtf = this.transformToRTF(template);
-    		  NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, m_xcontext, template)).convertToNodeset();    	  
-    		  m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, m_xcontext);
+    		  if (XslTransformData.m_xsl_message_rSeq == null) {
+    			  // An XSL stylesheet doesn't contain xsl:message
+    			  // instruction.
+    			  executeChildTemplates(template, true);
+    		  }
+    		  else {
+    			  // An XSL stylesheet contains one or more xsl:message
+    			  // instructions.
+    			  int rootNodeHandleOfRtf = this.transformToRTF(template);
+    			  NodeList nodeList = (new XRTreeFrag(rootNodeHandleOfRtf, m_xcontext, template)).convertToNodeset();    	  
+    			  m_xsl_transform_result_with_message = new XNodeSetForDOM(nodeList, m_xcontext);
+    		  }
     	  }
 
     	  if (m_debug)
@@ -3889,10 +3928,10 @@ public class TransformerImpl extends Transformer
 
     synchronized (m_reentryGuard)
     {
-      if (listener == null)
-        throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_NULL_ERROR_HANDLER, null)); //"Null error handler");
+    	if (listener == null)
+    		throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_NULL_ERROR_HANDLER, null)); //"Null error handler");
 
-      m_errorHandler = listener;
+    	m_errorHandler = listener;
     }
   }
 
diff --git a/src/main/java/org/apache/xpath/functions/XSL3FunctionService.java b/src/main/java/org/apache/xpath/functions/XSL3FunctionService.java
index 099ff297e..e16a07830 100644
--- a/src/main/java/org/apache/xpath/functions/XSL3FunctionService.java
+++ b/src/main/java/org/apache/xpath/functions/XSL3FunctionService.java
@@ -179,6 +179,8 @@ public class XSL3FunctionService {
     	XObject evalResult = null;
 
     	SourceLocator srcLocator = xctxt.getSAXLocator();
+    	
+    	final int sourceNode = xctxt.getCurrentNode();
 
     	try {        
     		XSL3ConstructorOrExtensionFunction funcObj = xpathExpr;
@@ -241,6 +243,15 @@ public class XSL3FunctionService {
     						if (elemTemplateElement1 instanceof ElemUsePackage) {
     							// Resolve function call reference
     							
+    							ElemUsePackage elemUsePackage2 = (ElemUsePackage)elemTemplateElement1;
+    							XPath useWhenExpr = elemUsePackage2.getUseWhen();
+    							XObject xObj = useWhenExpr.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+    							if (!xObj.bool()) {
+    							   elemTemplateElement1 = elemTemplateElement1.getNextSiblingElem();
+    							   
+    							   continue;
+    							}
+    							
     							System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.XSL3TransformerFactoryImpl");
 
     							try {
@@ -249,7 +260,7 @@ public class XSL3FunctionService {
 
     								ElemUsePackage elemUsePackage = (ElemUsePackage)elemTemplateElement1;
     								AVT packageAvt = elemUsePackage.getName();
-    								String packageName = packageAvt.evaluate(xctxt, xctxt.getCurrentNode(), xctxt.getNamespaceContext());
+    								String packageName = packageAvt.evaluate(xctxt, sourceNode, xctxt.getNamespaceContext());
 
     								DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
     								dfactory.setNamespaceAware(true);
@@ -342,8 +353,20 @@ public class XSL3FunctionService {
     					// Evaluate XSL stylesheet function call
     					
     					ElemFunction elemFunction = (ElemFunction)elemTemplate;
-
-    					evalResult = elemFunction.evaluateXslFunction(transformerImpl, xslFuncArgSequence);
+    					
+    					XPath useWhenExpr = elemFunction.getUseWhen();
+                        if (useWhenExpr != null) {
+                        	XObject xObj = useWhenExpr.execute(xctxt, sourceNode, xctxt.getNamespaceContext());
+                        	if (xObj.bool()) {
+                        	   evalResult = elemFunction.evaluateXslFunction(transformerImpl, xslFuncArgSequence);
+                        	}
+                        	else {
+                        	   evalResult = new ResultSequence();
+                        	}
+                        }
+                        else {
+    					    evalResult = elemFunction.evaluateXslFunction(transformerImpl, xslFuncArgSequence);
+                        }
 
     					if ((evalResult instanceof XPathNamedFunctionReference) && (funcExtArgStrList != null)) {
     						XPathNamedFunctionReference xpathNamedFunctionReference = (XPathNamedFunctionReference)evalResult;    					   


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@xalan.apache.org
For additional commands, e-mail: commits-help@xalan.apache.org