XSLT创建元素时如何添加带命名空间的属性?
解决XSLT生成XSLT时命名空间属性报错的问题
你遇到的报错是因为直接用<xsl:attribute name="xmlns:msxsl">创建命名空间声明属性的方式不符合XSLT规范。XSLT处理器会将xmlns视为一个未定义的前缀,从而抛出"Prefix is not defined"错误。而xlink是普通属性,没有涉及命名空间前缀解析,所以可以正常生成。
下面提供两种可行的解决方案:
方案一:直接在<xsl:element>上声明命名空间
在创建目标xsl:stylesheet元素时,直接在<xsl:element>标签内添加需要的命名空间声明,XSLT处理器会自动将这些声明输出为结果元素的属性:
<xsl:element name="xsl:stylesheet" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:xlink="http://www.w3.org/1999/xlink"> <xsl:attribute name="version">1.0</xsl:attribute> <xsl:attribute name="exclude-result-prefixes">msxsl</xsl:attribute> <xsl:apply-templates select="Root"/> </xsl:element>
生成的结果XSLT中,xsl:stylesheet元素会自动包含xmlns:msxsl和xmlns:xlink属性,无需单独用<xsl:attribute>创建。
方案二:使用<xsl:attribute>指定命名空间URI
如果需要通过<xsl:attribute>单独创建命名空间声明,要指定namespace属性为http://www.w3.org/2000/xmlns/(XML命名空间声明的标准URI),name属性写前缀名即可:
<xsl:element name="xsl:stylesheet"> <xsl:attribute name="version">1.0</xsl:attribute> <!-- 正确生成xmlns:msxsl属性 --> <xsl:attribute name="msxsl" namespace="http://www.w3.org/2000/xmlns/">urn:schemas-microsoft-com:xslt</xsl:attribute> <xsl:attribute name="xlink">http://www.w3.org/1999/xlink</xsl:attribute> <xsl:attribute name="exclude-result-prefixes">msxsl</xsl:attribute> <xsl:apply-templates select="Root"/> </xsl:element>
这种方式明确告诉XSLT处理器,这个属性是一个命名空间声明,而非普通属性,从而避免前缀未定义的错误。
内容的提问来源于stack exchange,提问作者user3297232
相关产品推荐
相关产品推荐

