复制节点和子元素(如果仅发生一次)

时间:2019-01-11 14:47:05

标签: xslt xslt-1.0

如果节点和它的子元素在xml中仅出现一次,则需要复制它。否则,不应修改xml。例如,在下面的xml中,如果<dataList>仅出现一次,则再复制一次。如果没有,请不要完全更改xml。请只使用XSLT 1.0。

Input XML

 <?xml version="1.0" encoding="UTF-8"?>
<API>
   <Token/>
   <root>
     <dataList>
        <addressOne>1</addressOne>
        <addressTwo/>
        <bkdn/>
     </dataList>
   </root>
 </API>

预期的输出xml

<?xml version="1.0" encoding="UTF-8"?>
 <API>
   <Token/>
   <root>
      <dataList>
         <addressOne>1</addressOne>
         <addressTwo/>
         <bkdn/>
      </dataList>
      <dataList>
         <addressOne>1</addressOne>
         <addressTwo/>
         <bkdn/>
       </dataList>
     </root>
</API>

1 个答案:

答案 0 :(得分:0)

据我的理解,我想解决它:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="1.0">

    <xsl:output indent="yes"/>

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

    <xsl:template match="root">
        <xsl:copy>

        <xsl:choose>

            <!-- If you are looking for the dataList occurance then use count -->
            <xsl:when test="count(dataList) = 1">

            <!-- If you are looking for the dataList/addressOne value = 1 occurance then use below -->

        <!-- <xsl:when test="dataList/addressOne=1"> -->
                <xsl:apply-templates select="dataList"/>
                <xsl:apply-templates select="dataList"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="dataList"/>
            </xsl:otherwise>
        </xsl:choose>
        </xsl:copy>
    </xsl:template>



</xsl:stylesheet>