How to get started with XSLT? [closed]

2019-03-07 03:15发布

问题:

I have never done anything with XSLT and I need to write an XSLT script or some other script to add a header and a trailer to XML files that we are FTPing to a location.

How can I do this?

回答1:

XSLT Quick Start

  1. Create a sample input XML file:

    <root>
      <header>This header text</header>
      <body>This is body text.</body>
    </root>
    
  2. Run the identity transform,

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" indent="yes"/>
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    
  3. And be sure that you generate the same XML as the input XML:

    <root>
      <header>This header text</header>
      <body>This is body text.</body>
    </root>
    
  4. Then add another template to treat the body differently

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>
      <!-- New template for body element -->
      <xsl:template match="body">
        <!-- Copy body as-is like in the default identity template -->
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
        <!-- Do something new here: Add a footer element -->
        <footer>This is new footer text</footer>
      </xsl:template>
    </xsl:stylesheet>
    
  5. And run the new XSLT to generate new XML output containing a footer this time:

    <root>
      <header>This header text</header>
      <body>This is body text.</body>
      <footer>This is new footer text</footer>
    </root>
    
  6. Continue in this manner until your output is fully as desired.

Recommended XSLT Resources

  • XSLT 2.0 and XPath 2.0 Programmer's Reference by Michael Kay
  • XSLT 2.0 and 1.0 Foundations by Dimitre Novatchev
  • XSLT Tutorials by Jeni Tennison


标签: xml xslt