0

I need extract <C></C>, by passing a parameter to the xslt like below

<C>
<D></D>
<D></D>
</C>

from the below XML using xslt.

<A>
<B/>
<C>
<D></D>
<D></D>
</C>
<E><D></D></E>
</A>

If I able to set the value for the element as "C", how I able to perform the above operation. My current xslt template like below.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <!-- Identity transform -->
   <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()" />
      </xsl:copy>
   </xsl:template>
   <xsl:param name="element" />
   <xsl:template match="/">
      <$element>
         <xsl:processing-instruction name="xml-multiple">
            <xsl:value-of select="local-name(//D)" />
         </xsl:processing-instruction>
         <xsl:copy-of select="/A/$element/D" />
      </$element>
   </xsl:template>
</xsl:stylesheet>
1
  • thx a lot Potame its worked for me. Could you tell me is this possible? <xsl:if test="$element = 'C'">$element ="E"</xsl:if> to get effected <E></E> tags Commented Jan 22, 2016 at 11:44

1 Answer 1

2

It's not possible to enter an element name as a parameter and use it directly in the XPath for the selects.

However you could refactor your stylesheet this way:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <!-- Identity transform -->
   <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()" />
      </xsl:copy>
   </xsl:template>
   <xsl:param name="element" select="'C'"/>
   <xsl:template match="/">
      <xsl:element name="{$element}">

         <xsl:processing-instruction name="xml-multiple">
            <xsl:value-of select="local-name(//D)" />
         </xsl:processing-instruction>

         <xsl:copy-of select="/A/*[name() = $element]/D" />
      </xsl:element>
   </xsl:template>
</xsl:stylesheet>

The result obtained :

<?xml version="1.0" encoding="UTF-8"?>
<C>
  <?xml-multiple D?>
  <D/><D/>
</C>

corresponds to the desired output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.