Rename XML elements using XSLT

前端 未结 2 1398
慢半拍i
慢半拍i 2021-02-04 22:30

I need to change some of the element names in the original XML. I am trying to do this with XSLT, but can\'t get it to work.

Here is a sample of XML:

&l         


        
相关标签:
2条回答
  • 2021-02-04 23:09

    The following template achieves the result you're looking for:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
        <xsl:output method="html" />
    
        <!-- Copy all elements and attributes from the source to the target -->
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
            </xsl:copy>
        </xsl:template>
    
        <!-- Transform the given elements to divs with class names matching the source element names -->
        <xsl:template match="itemtitle|poll|pcredit">
            <div class="{local-name(.)}">
              <xsl:value-of select="."/>
            </div>
        </xsl:template>
    
        <!-- Transform the section element to a div of class 'issuehead' -->
        <xsl:template match="section">
            <div class="issuehead">
                <xsl:value-of select="."/>
            </div>
        </xsl:template>
    
    </xsl:stylesheet> 
    

    If you'd like more well formed markup modify the xsl:output tag as follows:

    <xsl:output method="xml" 
        version="1.0" 
        encoding="UTF-8" 
        indent="yes" 
        omit-xml-declaration="yes" 
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" 
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    />
    
    0 讨论(0)
  • 2021-02-04 23:25

    For anything like this, start with an identity transform:

    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="node( ) | @*">
        <xsl:copy>
            <xsl:apply-templates select="@* | node( )"/>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>  
    

    This will just copy every node. But then you add additional templates to do what you need:

    <xsl:template match="section"> 
      <div class="issuehead">
          <xsl:apply-templates select="@* | node( )"/>
      </div>
    </xsl:template>
    

    This pattern should get you what you want.

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