如何在XSLT 2.0输出中省略指定命名空间?
问题描述
我有如下XML输入:
<?xml version="1.0" encoding="UTF-8"?> <item xmlns="http://www.p-corp.com/ns/pyxml" version="2.2" xml:lang="en-us"> <head> <title>Scope of application</title> <id>a71ad0e3e1ed569595c88b60421846ee</id> <version>2</version> </head> <body lang="en"> <section id="d29e3458" data-class="portrait smo-chapter-orientation-portrait smo-chapter-numbering-no numbering-no lvl- 1" data-type="Chapter"> <p class="smo-hide" data-role="heading" id="d29e3461">System requirements</p> <div data-role="block" id="d29e3525"/> </section> </body> </item>
通过XSLT 2.0转换后得到如下HTML输出,其中<html>标签带了不需要的xmlns="http://www.p-corp.com/ns/pyxml"属性:
<!DOCTYPE HTML> <html xmlns="http://www.p-corp.com/ns/pyxml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Scope of application</title> <meta name="id" content="32a80e1803f0966289c5c7d3075abcd8"/> </head> </html>
使用的样式表如下:
<?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:lang="en" xmlns="http://www.p-corp.com/ns/pyxml" xpath-default-namespace="http://www.p-corp.com/ns/pyxml" exclude-result-prefixes="" > <xsl:output method="html" encoding="utf-8" indent="yes"/> <xsl:template match="/*"> <html> <xsl:apply-templates select="*" /> </html> </xsl:template> <!-- other template rules, omitted for readability --> </xsl:stylesheet>
尝试用exclude-result-prefixes=""无法移除该命名空间,求解决方法。
解决方案
问题根源是样式表中声明的默认命名空间xmlns="http://www.p-corp.com/ns/pyxml",它会让所有未指定命名空间的输出元素自动归属到该命名空间。要移除输出里的命名空间,按以下步骤调整:
删除样式表的默认命名空间声明
删掉原样式表中的xmlns="http://www.p-corp.com/ns/pyxml",这个声明是输出元素带上命名空间的直接原因。保留
xpath-default-namespace确保输入匹配
保留xpath-default-namespace="http://www.p-corp.com/ns/pyxml",这样XSLT依然能正确匹配输入XML中带该命名空间的元素。优化
exclude-result-prefixes配置
改为exclude-result-prefixes="#all",自动排除所有未使用的命名空间前缀,避免冗余声明出现在输出中。
修改后的核心样式表代码如下:
<?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xml:lang="en" xpath-default-namespace="http://www.p-corp.com/ns/pyxml" exclude-result-prefixes="#all" > <xsl:output method="html" encoding="utf-8" indent="yes"/> <xsl:template match="/*"> <html> <xsl:apply-templates select="*" /> </html> </xsl:template> <!-- 为HTML元素添加模板,确保输出无命名空间 --> <xsl:template match="head"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <xsl:apply-templates select="title"/> <meta name="id" content="32a80e1803f0966289c5c7d3075abcd8"/> </head> </xsl:template> <xsl:template match="title"> <title> <xsl:value-of select="."/> </title> </xsl:template> <!-- other template rules, omitted for readability --> </xsl:stylesheet>
关键说明
- 移除默认命名空间后,输出的
<html>、<head>等元素会默认属于无命名空间,不会再带上xmlns属性。 exclude-result-prefixes="#all"会自动清理所有未在输出中使用的命名空间前缀,进一步确保输出简洁。
这样调整后,生成的HTML就不会包含多余的命名空间属性了。
内容的提问来源于stack exchange,提问作者ondrums
相关产品推荐
相关产品推荐

