关于XSLT中apply-templates元素参数传值与调用逻辑的疑问
Let me walk you through this XSLT snippet step by step to untangle the call chain and parameter passing—this kind of selector and mode logic can feel opaque until you break it down piece by piece.
First, the apply-templates Core Behavior
The <xsl:apply-templates> element is XSLT’s way of saying "find the nodes matching this selector, then hand them off to the appropriate template for processing." Let’s break down your specific selector:
DocumentType[string(text())]: This filters allDocumentTypechild nodes of the current context node to only those that have non-empty text content. Thestring(text())check converts the node’s text to a string; if it’s not blank (i.e., has actual text), the node is included in the selection.[1]: This grabs just the first node from that filtered list—so only the very firstDocumentTypenode with text content gets processed here.
The mode="XmlString" Purpose
The mode attribute is like a "filter" for templates. XSLT lets you have multiple templates that match the same node type (DocumentType in this case), but only the template that declares mode="XmlString" will respond to this apply-templates call. This prevents conflicts if you have other templates handling DocumentType nodes for different purposes (like formatting for HTML vs. generating raw XML strings).
Parameter Passing with xsl:with-param
The <xsl:with-param> line is explicitly passing a named parameter to the target template:
name="name": This defines the parameter’s name (the template will need to declare a matching<xsl:param name="name"/>to receive it).select="'DocumentType'": This sets the parameter’s value to the literal stringDocumentType(note the nested single quotes inside the double-quotedselectattribute—this is how you define string literals in XSLT select expressions).
What the Target Template Looks Like (Example)
To use this parameter, the corresponding template would look something like this:
<xsl:template match="DocumentType" mode="XmlString"> <!-- Declare the parameter to receive the value --> <xsl:param name="name"/> <!-- Use the parameter in processing—here's a common use case --> <xsl:element name="{$name}"> <!-- Output the text content of the matched DocumentType node --> <xsl:value-of select="."/> </xsl:element> </xsl:template>
Full Call Chain Recap
- Starting from the current context node (where the
apply-templatesis placed in your XSLT), the selector finds the first childDocumentTypenode with non-empty text. - XSLT looks for a template that matches
DocumentTypeand hasmode="XmlString". - It passes the
nameparameter (value:DocumentType) to that template. - The template uses the parameter (via
$name) along with the matchedDocumentTypenode’s content to generate output.
内容的提问来源于stack exchange,提问作者Leth

