Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

xslt - XSL That Returns the XML unchanged

I am looking for a XSL snippet that simply returns the XML unaltered. It sounds trivial but I can't seem to find an example anywhere on the web. Any help out there?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to copy the complete XML document, it is necessary to have a template that matches the root. This might be:

     <xsl:template match="/">

or

     <xsl:template match="node()">

Then a single copying of the current node (the root node) is just sufficient:

     <xsl:copy-of select="."/>

So, one such complete transformation is:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
      <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

Although this is probably the simplest such transformation, XSLT programmers use another one, widely known as the identity transformation or the identity rule:

<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>

The reson the identity transformation is considered to be one the most fundamental XSLT design patterns and to be so massively used, is that by overriding this template rule with other, more specific templates, one can very easily perform a variety of operations that otherwise will be difficult. Examples are deleting a particular (set of) element(s) that have a specific name or satisfy some other condition, renaming particular elements, changing the namespace of particular elements, creating new children or siblings of particular elements, ..., etc.

For more information and code snippets using the identity transformation, do look here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...