aurel
aurel

Reputation: 1137

How to get the namespace of a node in xslt?

I'm propably doing something stupid here, I bet there is an easier way... I need to access namespace of a node. Elements in my xml looks for example like this:

<somenamespace:element name="SomeName">

Then in my xslt I access this elements with:

 <xsl:template  match="*[local-name()='element']">
    <xsl:variable name="nodename">
      <xsl:value-of select="local-name(current())"/>
    </xsl:variable>

<xsl:choose>
  <xsl:when test="contains($nodename,':')">

Well, of course it doesn't work, because there is no "somenamespace" namespace even in template match...

Can anyone guide me, what am I looking for?

Upvotes: 6

Views: 9479

Answers (3)

Michael Kay
Michael Kay

Reputation: 163262

It looks to me as if you want to test whether the node is in a non-null namespace. The correct way to do that is

namespace-uri() != ''

You shouldn't be looking at whether the lexical name has a prefix or contains a colon, because if the node is in a namespace then it can be written either with a prefix or without, and the two forms are equivalent.

But I'm guessing as to what your real, underlying, requirement is.

Upvotes: 6

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

From OP's comment:

I'm looking for a way to access the "somenamespace" prefix.

You can access the prefix of the current node name by:

substring-before(name(), ':")

Another way:

substring-before(name(), local-name())

The above produces either the empty string '' or the prefix, followed by the ':' character.

To check if the name of the current node is prefixed:

not(name() = local-name())

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

You are looking for name function, e..g.:

<xsl:value-of select="name()"/>

returns somenamespace:element

Upvotes: 3

Related Questions