简体   繁体   中英

XSLT for Variable Element Name for multiple same elements

I have a piece of XML data with information for multiple persons represented as -

<phoneContact>
    <firstName>XXXXX</firstName>
    <middleName>Y</middleName>
    <lastName>ZZZZZ</lastName>
    <phone>1234567890</phone>
</phoneContact>
<phoneContact>
    <firstName>AAAA</firstName>
    <middleName>B</middleName>
    <lastName>CCCCC</lastName>
    <phone>9876543210</phone>
</phoneContact>

There may be any number of persons available. I want to transform this into -

<phoneContact1>
    <firstName>XXXXX</firstName>
    <middleName>Y</middleName>
    <lastName>ZZZZZ</lastName>
    <phone>1234567890</phone>
</phoneContact1>
<phoneContact2>
    <firstName>AAAA</firstName>
    <middleName>B</middleName>
    <lastName>CCCCC</lastName>
    <phone>9876543210</phone>
</phoneContact2>

.. and so forth. How do I construct an XSL for-each code that creates multiple such different element names ?

Thank you for any help with this.

Inside the loop over the phoneContact elements you can use <xsl:element> and the the position function to create your numbered phoneContacts :

<xsl:for-each select="phoneContact"> 
    <xsl:element name="phoneContact{position()}">
     ...
   </xsl:element>
</xsl:for-each>

we can implement using identity function as below

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
  <xsl:template match="/a/phoneContact">
<xsl:element name="phoneContact{position()}">

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

</xsl:element>
  </xsl:template>

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