简体   繁体   中英

XSLT Tag with N Values to Tag with One Value

I have this situation down there:

<GetNewOrdersResponse>
  <GetNewOrdersResult>
    <Receipts>
      <IdOrder>1</IdOrder>
      <IdOrder>2</IdOrder>
      <IdOrder>3</IdOrder>
    </Receipts>
  </GetNewOrdersResult>
</GetNewOrdersResponse>

And I want to transform to this structure

<GetNewOrdersResponse>
  <GetNewOrdersResult>
    <Receipts>
      <IdOrder>1</IdOrder>
    </Receipts>
    <Receipts>
      <IdOrder>2</IdOrder>
    </Receipts>
    <Receipts>
      <IdOrder>3</IdOrder>
    </Receipts>
  </GetNewOrdersResult>
</GetNewOrdersResponse>

I have tried this code, but I didn't get any success:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <ns0:Test xmlns:ns0="http://test/GetNewOrders">
      <GetNewOrdersResponse>
        <GetNewOrdersResult>
          <Receipts>
            <IdOrder>
            <xsl:for-each select="GetNewOrdersResponse/GetNewOrdersResult/Receipts/IdOrder">
              <xsl:value-of select="IdOrder"/>
            </xsl:for-each>
            </IdOrder>
          </Receipts>
        </GetNewOrdersResult>
      </GetNewOrdersResponse>
    </ns0:Test>
  </xsl:template>
</xsl:stylesheet>

This is fairly trivial, using the identity transform template as the rule and a couple of exceptions to the rule:

<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="Receipts">
    <xsl:apply-templates select="@*|node()"/>
</xsl:template>

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

</xsl:stylesheet>

Or, if you prefer going with the logic of your attempt:

<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:template match="/">
    <GetNewOrdersResponse>
        <GetNewOrdersResult>
            <xsl:for-each select="GetNewOrdersResponse/GetNewOrdersResult/Receipts/IdOrder">
                <Receipts>
                    <xsl:copy-of select="."/>
                </Receipts>
            </xsl:for-each>
        </GetNewOrdersResult>
    </GetNewOrdersResponse>
</xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM