質問

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.

役に立ちましたか?

解決

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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top