简体   繁体   中英

Transform XML replacing nodes

I need to transform a XML. I tried XSLT transformations unsuccessfully. I am new on it.

Source:

<md>    
<mi>     
  <mt>rock</mt>
  <mt>classic</mt>
  <mt>pop</mt>
  <mv>
    <moid>blue</moid>
    <r>2</r>
    <r>4</r>
    <r>6</r>
  </mv>
  <mv>
    <moid>yellow</moid>
    <r>1</r>
    <r>5</r>
    <r>33</r>
  </mv>
  <mv>
    <moid>green</moid>
    <r>22</r>
    <r>0</r>
    <r>10</r>
  </mv>
</mi>
</md>

Target:

<md>    
<mi>     
  <mt>rock</mt>
  <mt>classic</mt>
  <mt>pop</mt>
  <mv>
    <moid>blue</moid>
    <rock>2</rock>
    <classic>4</classic>
    <pop>6</pop>
  </mv>
  <mv>
    <moid>yellow</moid>
    <rock>1</rock>
    <classic>5</classic>
    <pop>33</pop>
  </mv>
  <mv>
    <moid>green</moid>
    <rock>22</rock>
    <classic>0</classic>
    <pop>10</pop>
  </mv>     
</mi>
</md>

Basically, I need to replace 'r'tag nodes with the correct value of mt nodes based on the position. For instance, the first 'r' tag node(the one with value 2) must be replaced with tag 'rock'. Any advise on the solution would be appreciate. Thanks and Best Regards, Gav.

Here's one way you could look at it:

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="*"/>

<xsl:key name="cat" match="mt" use="count(preceding-sibling::mt)" />

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

<xsl:template match="r">
    <xsl:element name="{key('cat', count(preceding-sibling::r))}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element >
</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