当根元素具有默认 namespace 属性时,我在 xslt 行为中遇到了一个特殊的差异,而不是当它没有时。
我想知道为什么会出现这种差异。
XML 输入是
<root>
<content>xxx</content>
</root>
应用以下转换时
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<root>
<xsl:apply-templates/>
</root>
</xsl:template>
<xsl:template match="content">
<w>x</w>
</xsl:template>
</xsl:stylesheet>
结果是预期的
<?xml version="1.0" encoding="UTF-8"?>
<root>
<w>x</w>
</root>
但是当同样的变换应用到
<root xmlns="http://test.com">
<content>xxx</content>
</root>
结果是不同的,基于仅默认模板的应用(它有效地输出文本节点值'xxx'):
<?xml version="1.0" encoding="UTF-8"?>
<root>xxx</root>
添加
如果这是这种情况下的预期行为,那么在第二种情况下需要什么匹配属性值来匹配 content
元素?
最佳答案
这是 XPath/XSLT 中最多的 FAQ。
没有前缀的元素名称被 XPath 视为属于“无命名空间”。
if the QName does not have a prefix, then the namespace URI is null.
因此,在具有默认命名空间的文档中,对具有无前缀名称(例如“someName”)的元素的引用不会选择任何内容,因为 XML 文档中的“无命名空间”中没有任何元素,但是 someName
表示名称为“someName”的元素,属于“无命名空间”。
解决方案:
如果我们想通过名称选择一个元素,我们必须为该名称添加前缀,并且该前缀必须与默认命名空间相关联。
这个转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://test.com" exclude-result-prefixes="x">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<root>
<xsl:apply-templates/>
</root>
</xsl:template>
<xsl:template match="x:content">
<w>x</w>
</xsl:template>
</xsl:stylesheet>
应用于具有默认命名空间的提供的 XML 文档时:
<root xmlns="http://test.com">
<content>xxx</content>
</root>
产生想要的、正确的结果:
<root>
<w>x</w>
</root>
关于xslt - xsl :template match attribute: how related to default namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10157130/