Copy parallel element as child element of another

2019-09-06 03:27发布

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <order orderId="12345">
      <cartId>12346</cartId>
   </order>
   <orderPayment paymentId="1234">
      <debitCardPayment>
         <chargeAmount currencyCode="USD">22.20</chargeAmount>
         <debitCard>
            <PIN>1234</PIN>                
         </debitCard>
      </debitCardPayment>
   </orderPayment>
</root>

I have the input xml as above.I need to move the orderPayment element in order.I wrote as follows

<xsl:template match="v1:order"> 
        <xsl:apply-templates select="v1:Root/v1:orderPayment"/>
        <xsl:apply-templates select="@*|node()"/>           
      </xsl:template>

       <xsl:template match="v1:orderPayment">        
         <xsl:apply-templates select="@*|node()"/>
      </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:choose>
            <xsl:when test=".='' and count(@*)=0">
                <xsl:apply-templates select="@*|node()"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates select="@*|node()"/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template> 

OUTPUT

<order>
  .....
 <orderPayment>
   .....
</orderPayment>
</order>

I am not getting the expected output.What is the mistake?

Thanks in advance...

标签: xml xslt xpath
1条回答
三岁会撩人
2楼-- · 2019-09-06 03:39

Given your input, the following stylesheet:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="order">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy-of select="../orderPayment"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="orderPayment"/>

</xsl:stylesheet>

will return:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <order orderId="12345">
      <cartId>12346</cartId>
      <orderPayment paymentId="1234">
         <debitCardPayment>
            <chargeAmount currencyCode="USD">22.20</chargeAmount>
            <debitCard>
               <PIN>1234</PIN>
            </debitCard>
         </debitCardPayment>
      </orderPayment>
   </order>
</root>
查看更多
登录 后发表回答