You are viewing a plain text version of this content. The canonical link for it is here.
Posted to j-users@xalan.apache.org by Cynepnaxa <P....@cft.ru> on 2007/09/07 04:12:17 UTC

Extension element with subelements

Hi, everybody!
I start to write simple extension element, but a problem occurs. I want to
access extension element's subelements in java+xalan. My xsl contains
following block of code:
<my-ext:request>
<body><xsl:value-of select="$body"/></body>
<contentType>text/html</contentType>
<metaData><![CDATA[<?xml version="1.0" encoding="utf-8"?>]]><metaData>
<xsl:value-of select="$metaData"/>
</metaData>
</metaData>
</my-ext:request>
In extension element Java-method i have "XSLProcessorContext context" and
"ElemExtensionCall elem". I can get contentType by calling for example
"elem.getFirstChild().getNextSibling().getFirstChild().getTextContent()",
but i want to access subelements by tag name(for example, by
elem.getElementsByTagName("metadata"), or XPath). I have no idea how to
access in java content of $body variable and xml - encapsulated $metaData.
All google - examples shining no light. Is simple xslt - subelements access
method exist? Big thanx for help.
P.S. Sorry for my English. I hope you understand me.

-- 
View this message in context: http://www.nabble.com/Extension-element-with-subelements-tf4395665.html#a12534751
Sent from the Xalan - J - Users mailing list archive at Nabble.com.


Re: Extension element with subelements

Posted by John Gentilin <ge...@eyecatching.com>.
Oops... this might be what you are after instead...
executeChildTemplatesToXML or ToString or ToXMLString
may be what you are after..


/**
 * A repository for common functions that can be used but the extension
 * functions and extension elements.
 *
 *
 * Title:       Base Functions
 * Copyright:   Copyright (c) 2005
 * Company:     Eye Catching Solutions Inc.
 * @version     1.0
 * @author      John Gentilin
 */


public class BaseFunctions
{
  private static Category m_Log = 
Category.getInstance("RapidXSL.Interface");
  private static DocumentBuilderFactory  m_dfactory = null;
  private static DocumentBuilder  m_docBuilder = null;


  /**
   * @param context
   * @param elem
   * @throws TransformerException
   */
  protected void executeChildTemplates( XSLProcessorContext context, 
ElemExtensionCall elem ) throws TransformerException
  {
    TransformerImpl transf = context.getTransformer();
    transf.executeChildTemplates(elem,
        context.getContextNode(),
        context.getMode(), transf.getResultTreeHandler());
  }
   
 
  /**
   * @param context
   * @param elem
   * @throws TransformerException
   */
  protected Document executeChildTemplatesToXML(Document doc, 
XSLProcessorContext context, ElemExtensionCall elem ) throws 
XMLServerException
  {
    DOMBuilder builder = null;
     
    TransformerImpl transformer = context.getTransformer();
     
    try
    {
      builder = new DOMBuilder(doc);
       
      transformer.executeChildTemplates(elem,
          context.getContextNode(),
          context.getMode(), builder);
 
    }
    catch (Exception e)
    {
      throw new XMLServerException("RXSL_IFACE", "XSL Interface Error - 
" + e.getLocalizedMessage());
    }
    return doc;
  }
 
  /**
   * @param context
   * @param elem
   * @throws TransformerException
   */
  protected String executeChildTemplatesToString(XSLProcessorContext 
context, ElemExtensionCall elem ) throws XMLServerException
  {
         
    TransformerImpl transformer = context.getTransformer();
     
    try
    {
      TextSerializationHandler handler = new TextSerializationHandler();
       
      transformer.executeChildTemplates(elem,
          context.getContextNode(),
          context.getMode(), handler);
           
      return handler.toString();
 
    }
    catch (Exception e)
    {
      throw new XMLServerException("RXSL_IFACE", "XSL Interface Error - 
" + e.getLocalizedMessage());
    }
  }
 
  protected String executeChildTemplatestoXMLString(XSLProcessorContext 
context, ElemExtensionCall elem)
    throws TransformerException, SAXException
   {
      try
      {
        TransformerImpl transformer = context.getTransformer();
       
        // This should be worked on so that the output format can be
        // defined by a first child of the redirect element.
        OutputProperties format = transformer.getOutputFormat();
        Properties prop = format.getProperties();
        format.setProperty("indent","no");
        
format.setProperty("{http://xml.apache.org/xalan}indent-amount","0");
       
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        SerializationHandler serializer =
        transformer.createSerializationHandler(
          new StreamResult(ostream),
          format);
                
        serializer.startDocument();
       
        transformer.executeChildTemplates(elem,
        context.getContextNode(),
        context.getMode(), serializer);
           
        serializer.flushPending();
        serializer.endDocument();
        return ostream.toString("ISO-8859-1");
      }
      catch (UnsupportedEncodingException e)
      {
        m_Log.fatal("Error Encoding Bytes from XML - " + 
e.getLocalizedMessage());
        return new String();
      }
      
   }

 
 
  /**
   * Get the Node Value of a Stylesheet Element. This will be used to 
collect
   * the data value when populating a Control.....
   *
   * @return
   */
  protected String getNodeValue( ElemExtensionCall elem )
  {
    Node child = elem.getFirstChild();
    if (child != null)
    {
      return child.getNodeValue();
    }
     
    return null;
  }
   
  /**
    * Resolve the Attribute Selection for the fixed attribute "select"
    *
    * @return
    * @throws TransformerException
    */
   protected String getStringValueFromSelectExpr(XSLProcessorContext 
context, ElemExtensionCall elem  ) throws TransformerException
   {
     return getStringValueFromAttribute("select", context, elem);
   }
   
   /**
  * Find the Attribute named "attrib" and convert that to an XPath statement
  * that can be executed.
  *
  * Return null if the Attribute did not exist.
  *
  * @param attrib
  * @return
  * @throws TransformerException
  */
   
   protected static XPath getAttributeExpr( String attrib, 
XSLProcessorContext context, ElemExtensionCall elem ) throws 
TransformerException
   {
     String expr =
      elem.getAttribute (attrib,
                         context.getContextNode(),
                         context.getTransformer());
                         
     if(null != expr)
     {
       org.apache.xpath.XPathContext xctxt
         = context.getTransformer().getXPathContext();
         
       return new XPath(
             expr,
             elem,
             xctxt.getNamespaceContext(), XPath.SELECT);
     }
     
     return null;
     
   }
 
 
  /**
   *
   * Get the value of an Attribute. It will first try to treat the 
attribute as an XPath
   * if that fails then just return the attribute value itself.
   *
   * @param attrName
   * @param context
   * @param elem
   * @return
   */ 
  protected String getStringValueFromAttribute( String attrName, 
XSLProcessorContext context, ElemExtensionCall elem )
  {
      XPath path;
      String value = null;
      try
      {
        path = getAttributeExpr(attrName, context, elem);
        if (path != null)
        {
          XObject data = executeXPath(path, context, elem);
          if (data != null) value = data.xstr().toString();
        }
      }
      catch (TransformerException e)
      {
        value = elem.getAttribute(attrName);
      }
       
      if (value == null) value = "";
      return value;
  }
   
 
  /**
   * A helper function to execute an XPath Object.
   *
   * @param path
   * @return
   * @throws TransformerException
   */
  protected static XObject executeXPath( XPath path, XSLProcessorContext 
context, ElemExtensionCall elem ) throws TransformerException
  {
    org.apache.xpath.XPathContext xctxt
      = context.getTransformer().getXPathContext();
       
    return path.execute(xctxt, context.getContextNode(), elem);
  }

  protected Document getEmptyDocument()
  {
    initDocFactory();
    return m_docBuilder.newDocument();
  }
   
  protected static void initDocFactory()
  {
    if (m_dfactory != null) return;
    try
    {
      m_dfactory = DocumentBuilderFactory.newInstance();
      m_docBuilder = m_dfactory.newDocumentBuilder();
    }
    catch (Exception e)
    {
      m_Log.fatal("RapidXSL Interface, failure to init XML Subsystem - " 
+ e.getLocalizedMessage());
    }
  }
}
Cynepnaxa wrote:
> Hi, everybody!
> I start to write simple extension element, but a problem occurs. I want to
> access extension element's subelements in java+xalan. My xsl contains
> following block of code:
> <my-ext:request>
> <body><xsl:value-of select="$body"/></body>
> <contentType>text/html</contentType>
> <metaData><![CDATA[<?xml version="1.0" encoding="utf-8"?>]]><metaData>
> <xsl:value-of select="$metaData"/>
> </metaData>
> </metaData>
> </my-ext:request>
> In extension element Java-method i have "XSLProcessorContext context" and
> "ElemExtensionCall elem". I can get contentType by calling for example
> "elem.getFirstChild().getNextSibling().getFirstChild().getTextContent()",
> but i want to access subelements by tag name(for example, by
> elem.getElementsByTagName("metadata"), or XPath). I have no idea how to
> access in java content of $body variable and xml - encapsulated $metaData.
> All google - examples shining no light. Is simple xslt - subelements access
> method exist? Big thanx for help.
> P.S. Sorry for my English. I hope you understand me.
>
>   



Re: Extension element with subelements

Posted by John Gentilin <ge...@eyecatching.com>.
I am kind of coming into this half cocked, just scanning the list here...
Below I have copied some basic function I use to implement extensions
and extension elements.

The function getStringValueFromAttribute will properly retrive a variable,
XPath expression or just the contents of an Extension Element attribute..

This should be able to easily adopted this if you are using an Extension 
Function
and want to retrieve the value of a parameter.

Hopefully this is what you are after...

John G

 
  /**
   * Get the Node Value of a Stylesheet Element. This will be used to 
collect
   * the data value when populating a Control.....
   *
   * @return
   */
  protected String getNodeValue( ElemExtensionCall elem )
  {
    Node child = elem.getFirstChild();
    if (child != null)
    {
      return child.getNodeValue();
    }
     
    return null;
  }
   
  /**
    * Resolve the Attribute Selection for the fixed attribute "select"
    *
    * @return
    * @throws TransformerException
    */
   protected String getStringValueFromSelectExpr(XSLProcessorContext 
context, ElemExtensionCall elem  ) throws TransformerException
   {
     return getStringValueFromAttribute("select", context, elem);
   }
   
   /**
  * Find the Attribute named "attrib" and convert that to an XPath statement
  * that can be executed.
  *
  * Return null if the Attribute did not exist.
  *
  * @param attrib
  * @return
  * @throws TransformerException
  */
   
   protected static XPath getAttributeExpr( String attrib, 
XSLProcessorContext context, ElemExtensionCall elem ) throws 
TransformerException
   {
     String expr =
      elem.getAttribute (attrib,
                         context.getContextNode(),
                         context.getTransformer());
                         
     if(null != expr)
     {
       org.apache.xpath.XPathContext xctxt
         = context.getTransformer().getXPathContext();
         
       return new XPath(
             expr,
             elem,
             xctxt.getNamespaceContext(), XPath.SELECT);
     }
     
     return null;
     
   }
 
 
  /**
   *
   * Get the value of an Attribute. It will first try to treat the 
attribute as an XPath
   * if that fails then just return the attribute value itself.
   *
   * @param attrName
   * @param context
   * @param elem
   * @return
   */ 
  protected String getStringValueFromAttribute( String attrName, 
XSLProcessorContext context, ElemExtensionCall elem )
  {
      XPath path;
      String value = null;
      try
      {
        path = getAttributeExpr(attrName, context, elem);
        if (path != null)
        {
          XObject data = executeXPath(path, context, elem);
          if (data != null) value = data.xstr().toString();
        }
      }
      catch (TransformerException e)
      {
        value = elem.getAttribute(attrName);
      }
       
      if (value == null) value = "";
      return value;
  }
   
 
  /**
   * A helper function to execute an XPath Object.
   *
   * @param path
   * @return
   * @throws TransformerException
   */
  protected static XObject executeXPath( XPath path, XSLProcessorContext 
context, ElemExtensionCall elem ) throws TransformerException
  {
    org.apache.xpath.XPathContext xctxt
      = context.getTransformer().getXPathContext();
       
    return path.execute(xctxt, context.getContextNode(), elem);
  }

Erin Harris wrote:
>
> Hi,
>
> I don't think the variables will have been replaced by their values 
> when the extension is called.  Instead you could create a result tree 
> fragment and call an extension function passing in the result tree 
> fragment such as in the following example.
>
> Stylesheet:
>
> <?xml version="1.0"?>
> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>                 xmlns:xalan="http://xml.apache.org/xalan"
>                 xmlns:myclass="MyClass"
>                 extension-element-prefixes="myclass"
>                 version="1.0">
>
>
>   <xalan:component prefix="myclass" functions="process">
>     <xalan:script lang="javaclass" src="MyClass"/>
>   </xalan:component>
>  
>   <xsl:variable name="var1" select="'This is variable 1.'"/>
>   <xsl:variable name="var2" select="'This is variable 2.'"/>
>   <xsl:variable name="rtf">
>     <elem1 number="1">
>       <xsl:value-of select="$var1"/>
>     </elem1>
>     <elem2 number="2">
>       <xsl:value-of select="$var2"/>
>     </elem2>
>   </xsl:variable>
>
>   <xsl:template match="/">
>     <out>
>       <xsl:value-of select="myclass:process($rtf)"/>
>     </out>
>   </xsl:template>
>  
> </xsl:stylesheet>
>
> MyClass.java:
>
> *import* org.w3c.dom.NamedNodeMap;
> *import* org.w3c.dom.Node;
> *import* org.w3c.dom.NodeList;
>
> *public* *class* MyClass {
>
>     *public* *void* process(NodeList rtf) {
>         *for* (*int* i = 0; i < rtf.getLength(); i++) {
>             processNode(rtf.item(i), "");
>         }
>     }
>    
>     *private* *void* processNode(Node node, String indent) {
>         System./out/.println(indent + "Name: " + node.getNodeName() + 
> ", Value: " + node.getNodeValue());
>         NamedNodeMap map = node.getAttributes();
>         *for* (*int* i = 0; i < map.getLength(); i++) {
>             Node attr = map.item(i);
>             System./out/.println(indent + "    Attr: " + 
> attr.getNodeName() + ", Value: " + attr.getNodeValue());
>         }
>         NodeList nodes = node.getChildNodes();
>         *for* (*int* i = 0; i < nodes.getLength(); i++) {
>             processNode(nodes.item(i), indent + "    ");
>         }
>     }
>    
> }
>
> The output from the processNode method is:
>
> Name: #document, Value: null
>     Name: elem1, Value: null
>         Attr: number, Value: 1
>         Name: #text, Value: This is variable 1.
>     Name: elem2, Value: null
>         Attr: number, Value: 2
>         Name: #text, Value: This is variable 2.
>
>
> Erin Harris
>
>
>
>
> *Cynepnaxa <P....@cft.ru>*
>
> 06/09/2007 10:12 PM
>
> 	
> To
> 	xalan-j-users@xml.apache.org
> cc
> 	
> Subject
> 	Extension element with subelements
>
>
>
> 	
>
>
>
>
>
>
> Hi, everybody!
> I start to write simple extension element, but a problem occurs. I want to
> access extension element's subelements in java+xalan. My xsl contains
> following block of code:
> <my-ext:request>
> <body><xsl:value-of select="$body"/></body>
> <contentType>text/html</contentType>
> <metaData><![CDATA[<?xml version="1.0" encoding="utf-8"?>]]><metaData>
> <xsl:value-of select="$metaData"/>
> </metaData>
> </metaData>
> </my-ext:request>
> In extension element Java-method i have "XSLProcessorContext context" and
> "ElemExtensionCall elem". I can get contentType by calling for example
> "elem.getFirstChild().getNextSibling().getFirstChild().getTextContent()",
> but i want to access subelements by tag name(for example, by
> elem.getElementsByTagName("metadata"), or XPath). I have no idea how to
> access in java content of $body variable and xml - encapsulated $metaData.
> All google - examples shining no light. Is simple xslt - subelements 
> access
> method exist? Big thanx for help.
> P.S. Sorry for my English. I hope you understand me.
>
> -- 
> View this message in context: 
> http://www.nabble.com/Extension-element-with-subelements-tf4395665.html#a12534751
> Sent from the Xalan - J - Users mailing list archive at Nabble.com.
>
>


-- 
--------------------------------------
John Gentilin
Eye Catching Solutions Inc.
18314 Carlwyn Drive
Castro Valley CA 94546

    Contact Info
gentijo@eyecatching.com
Ca Office 1-510-881-4821
NJ Office 1-732-422-4917


Re: Extension element with subelements

Posted by Erin Harris <eh...@ca.ibm.com>.
Hi,

I don't think the variables will have been replaced by their values when 
the extension is called.  Instead you could create a result tree fragment 
and call an extension function passing in the result tree fragment such as 
in the following example.

Stylesheet:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xalan"
                xmlns:myclass="MyClass"
                extension-element-prefixes="myclass"
                version="1.0">


  <xalan:component prefix="myclass" functions="process">
    <xalan:script lang="javaclass" src="MyClass"/>
  </xalan:component>
 
  <xsl:variable name="var1" select="'This is variable 1.'"/>
  <xsl:variable name="var2" select="'This is variable 2.'"/>
  <xsl:variable name="rtf">
    <elem1 number="1">
      <xsl:value-of select="$var1"/>
    </elem1>
    <elem2 number="2">
      <xsl:value-of select="$var2"/>
    </elem2>
  </xsl:variable>

  <xsl:template match="/">
    <out>
      <xsl:value-of select="myclass:process($rtf)"/>
    </out>
  </xsl:template>
 
</xsl:stylesheet>

MyClass.java:

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MyClass {

    public void process(NodeList rtf) {
        for (int i = 0; i < rtf.getLength(); i++) {
            processNode(rtf.item(i), "");
        }
    }
 
    private void processNode(Node node, String indent) {
        System.out.println(indent + "Name: " + node.getNodeName() + ", 
Value: " + node.getNodeValue());
        NamedNodeMap map = node.getAttributes();
        for (int i = 0; i < map.getLength(); i++) {
            Node attr = map.item(i);
            System.out.println(indent + "    Attr: " + attr.getNodeName() 
+ ", Value: " + attr.getNodeValue());
        }
        NodeList nodes = node.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            processNode(nodes.item(i), indent + "    ");
        }
    }
 
}

The output from the processNode method is:

Name: #document, Value: null
    Name: elem1, Value: null
        Attr: number, Value: 1
        Name: #text, Value: This is variable 1.
    Name: elem2, Value: null
        Attr: number, Value: 2
        Name: #text, Value: This is variable 2.


Erin Harris





Cynepnaxa <P....@cft.ru> 
06/09/2007 10:12 PM

To
xalan-j-users@xml.apache.org
cc

Subject
Extension element with subelements







Hi, everybody!
I start to write simple extension element, but a problem occurs. I want to
access extension element's subelements in java+xalan. My xsl contains
following block of code:
<my-ext:request>
<body><xsl:value-of select="$body"/></body>
<contentType>text/html</contentType>
<metaData><![CDATA[<?xml version="1.0" encoding="utf-8"?>]]><metaData>
<xsl:value-of select="$metaData"/>
</metaData>
</metaData>
</my-ext:request>
In extension element Java-method i have "XSLProcessorContext context" and
"ElemExtensionCall elem". I can get contentType by calling for example
"elem.getFirstChild().getNextSibling().getFirstChild().getTextContent()",
but i want to access subelements by tag name(for example, by
elem.getElementsByTagName("metadata"), or XPath). I have no idea how to
access in java content of $body variable and xml - encapsulated $metaData.
All google - examples shining no light. Is simple xslt - subelements 
access
method exist? Big thanx for help.
P.S. Sorry for my English. I hope you understand me.

-- 
View this message in context: 
http://www.nabble.com/Extension-element-with-subelements-tf4395665.html#a12534751

Sent from the Xalan - J - Users mailing list archive at Nabble.com.