简体   繁体   中英

Using XSLT prepend element attribute to another attribute of another element

I am looking to do a transformation where I take the attribute of one element and prepend it to the attribute value of another. Here is an example of what I would like to do"

<Stuff>
               <subsystem value="ssname">
               <item value="A">This is my value</item>
               <item value="B">This is my other value</item>
               </subsystem>
</Stuff>

I want to make a transformation using xslt to do the following:

<Stuff>
               <subsystem value="ssname">
               <item value="ssname_A">This is my value</item>
               <item value="ssname_B">This is my other value</item>
               </subsystem>
</Stuff>

How can I do this with XSLT 1.0?

The following stylesheet uses the context of the matched item/@value to snag the value of the subsystem/@value using the expression: ../../@value . Alternatively, you could use /Stuff/subsystem/@value instead.

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

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

    <!-- specialized template for value attribute that concatenates 
         the subsystem/@value with the current @value -->
    <xsl:template match="item/@value">
        <xsl:attribute name="value">
            <xsl:value-of select="concat(../../@value, 
                                         '_', 
                                         .)"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

This transformation :

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

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

 <xsl:template match="item">
  <item value="{../@value}_{@value}">
   <xsl:apply-templates select="node()"/>
  </item>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document :

<Stuff>
    <subsystem value="ssname">
        <item value="A">This is my value</item>
        <item value="B">This is my other value</item>
    </subsystem>
</Stuff>

produces the wanted, correct result :

<Stuff>
   <subsystem value="ssname">
      <item value="ssname_A">This is my value</item>
      <item value="ssname_B">This is my other value</item>
   </subsystem>
</Stuff>

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