views:

183

answers:

4

In XSLT 1.0, you can get the local name or the namespaceUri of an XML element using the functions:

string local-name (node)

and

string namespace-uri(node)

but is there a standard function to get the prefix of an element having a qualified name ?

A: 

Can you do string manipulation on the result of the name(node) function to retrieve this?

Matthew Wilson
+3  A: 

Not as far as I know. If you're sure the node name has a prefix, you can use this:

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

or this, if you are not sure:

substring-before(
  name(), 
  concat(':', local-name())
)

The latter expression is based on the fact that substring-before() returns the empty string when the searched string is not found. This way it will work correctly for prefixed and unprefixed names.

Tomalak
A: 

For further nuances, I recommend reading "Perils of the name() function".

For example, only in XPath 2.0 can you reliably get the prefix of an element. In XPath 1.0, the prefix used by an element is not part of the data model.

Given the following XML:

<my:foo xmlns:my="http://example.com" xmlns:my2="http://example.com"/&gt;

The name() function in XPath 1.0 could legally return either "my:foo" or "my2:foo". But in XPath 2.0, it must return "my:foo".

Evan Lenz
A: 

Generally speaking, if you care about an element's prefix, you're doing it wrong. You should only care about what namespace it belongs to.

In your comment, you note that the API you're talking to requires you to provide a namespace and a namespace prefix. That's true, but the API you linked to doesn't actually care what the namespace prefix is - in fact, it will generate a namespace prefix randomly if you don't provide one.

If you're generating entire XML documents, it's nice if you have a one-to-one mapping of prefixes to namespace URIs; it makes the output easier to understand. But it really doesn't matter what those prefixes are.

Robert Rossney