xslt - xsl :template match attribute: how related to default namespace

标签 xslt xpath namespaces

当根元素具有默认 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 视为属于“无命名空间”。

W3C Xpath specification:

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/

相关文章:

ruby - 如何只获取没有命名空间的类名

xslt - 如何从一个 xhtml 文档中提取一个 div 部分到另一个 xhtml 文档中

xml - 为编码的 XML 值应用 XSLT 模板

xslt - 在 XSLT 中,我可以只运行一次模板吗

c# - XPath 选择匹配的节点

xml - 提取XML属性和节点值R

android - Appium:无法在 Android 混合应用程序中使用 Xpath 定位元素?

php - 单页上的 Concrete5 Express 列表的命名空间问题

c# - 如何在 .Net 2.0/C# 中将 StreamReader 转换为 XMLReader 对象

visual-studio - 命名空间浏览在工具和导入中正常工作,但在代码窗口中不能正常工作(导入行除外)