XSL模板无法匹配servlet元素问题求助
问题解决:XSL无法匹配XML中的servlet元素
问题核心是命名空间不匹配:你的XML文档中所有元素(包括<servlet>)都属于http://xmlns.jcp.org/xml/ns/javaee命名空间,但XSL里声明的是旧的Java EE命名空间http://java.sun.com/xml/ns/javaee,且匹配规则未绑定正确的命名空间前缀,导致模板无法命中目标元素。
修改后的完整XSL代码
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:jee="http://xmlns.jcp.org/xml/ns/javaee" xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <xsl:output method="xml" encoding="ISO-8859-1"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="jee:servlet"> <xsl:copy> <xsl:apply-templates select="@*"/> <init-param> <param-name>readonly</param-name> <param-value>true</param-value> </init-param> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
关键修改说明
- 将XSL中的命名空间声明改为与XML一致的
http://xmlns.jcp.org/xml/ns/javaee,保留前缀jee用于匹配。 - 匹配规则改为
jee:servlet,明确指定命名空间下的元素。 - 由于XSL设置了默认命名空间,新添加的
<init-param>会自动继承该命名空间,无需额外前缀。
扩展:匹配特定servlet
如果需要匹配指定名称的servlet(比如名为default的),只需修改模板的match属性:
<xsl:template match="jee:servlet[jee:servlet-name='default']"> <!-- 原有逻辑不变 --> </xsl:template>
内容的提问来源于stack exchange,提问作者robhyx
相关产品推荐
相关产品推荐

