How to replace a tag with another tag in xml using xsl

前端 未结 2 1378
予麋鹿
予麋鹿 2021-01-02 23:40

My xml file looks like below.

  
  86
  100
  1.0
           


        
相关标签:
2条回答
  • 2021-01-03 00:19

    This is the typical task for the identity transform (the first template rule in the transform below). Just two overrides (the last two rules).


    XSLT 1.0 tested under Saxon 6.5.5

    <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="name">
            <brlName><xsl:value-of select="."/></brlName>
        </xsl:template>
    
        <xsl:template match="brlVersion">
            <xsl:copy-of select="."/>
            <drlName><xsl:value-of select="preceding-sibling::name"/>_1.0</drlName>
        </xsl:template>
    
    </xsl:stylesheet>
    
    0 讨论(0)
  • 2021-01-03 00:27

    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()|@*" name="identity">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
     </xsl:template>
    
     <xsl:template match="name">
      <brlName><xsl:apply-templates select="node()|@*"/></brlName>
     </xsl:template>
    
     <xsl:template match="/*/*[last()]">
      <xsl:call-template name="identity"/>
       <drlName>86_1.0</drlName>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on the provided XML document:

    <rule>
        <name>86</name>
        <ruleId>100</ruleId>
        <ruleVersion>1.0</ruleVersion>
        <brlVersion>1.0</brlVersion>
    </rule>
    

    produces the wanted, correct result:

    <rule>
       <brlName>86</brlName>
       <ruleId>100</ruleId>
       <ruleVersion>1.0</ruleVersion>
       <brlVersion>1.0</brlVersion>
       <drlName>86_1.0</drlName>
    </rule>
    

    Explanation:

    1. Using and overriding the identity rule/template -- the most fundamental and powerful XSLT design pattern.

    2. Override on any element named name and creating an element named brlName (rename).

    3. Override on the last last element child of the top element. Calling the identity rule by name for this node (copying) and then creating an element named drlName with a specific text-node child as per the requirements.

    Using and overriding the identity rule/template is the most fundamental and powerful XSLT design pattern. You can learn more about it here.

    0 讨论(0)
提交回复
热议问题