XSLT Namespaces

萝らか妹 提交于 2020-01-30 05:19:57

问题


I have a basic question about XSLT Namespaces.
XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="myNamespace" exclude-result-prefixes="x">
    <xsl:template match="/">
        <newNode>
            <xsl:value-of select="x:Node1/x:Node2" />
        </newNode>
    </xsl:template>
</xsl:stylesheet>

This XSLT works correctly when I apply it to:

<Node1 xmlns="myNamespace">
    <Node2>ValueIWant</Node2>
</Node1>

But it does not find "ValueIWant" when I apply it to:

<ns0:Node1 xmlns:ns0="myNamespace">
    <Node2>ValueIWant</Node2>
</ns0:Node1>

I feel that I am just missing some basic understanding of XSLT namespaces. Any help is greatly appreciated.


回答1:


In your first input file:

<Node1 xmlns="myNamespace">
    <Node2>ValueIWant</Node2>
</Node1>

you defined the default namespace on node Node1. For Node1 and any of its child nodes (unless/until you redefine it in a child node), the empty namespace prefix is bound to myNamespace. So both Node1 and Node2 are in myNamespace.

In your second input file:

<ns0:Node1 xmlns:ns0="myNamespace">
    <Node2>ValueIWant</Node2>
</ns0:Node1>

You are defining the namespace prefix ns0 to point to myNamespace but you haven't defined a default namespace. So Node1 is in namespace myNamespace but Node2 is not in any namespace at all.

You xpath expression x:Node1/x:Node2 (with prefix x bound to myNamespace) is looking for elements Node1 with a child Node2 that are both in namespace myNamespace. In your second input file, Node2 is not in that namespace so the xpath expression doesn't match and you do not get ValueIWant as a result.

You can correct the second input file like this:

<ns0:Node1 xmlns:ns0="myNamespace">
    <ns0:Node2>ValueIWant</ns0:Node2>
</ns0:Node1>


来源:https://stackoverflow.com/questions/21237279/xslt-namespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!