XSLT: getting element prefix?

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

string local-name (node) 

and

 string namespace-uri(node) 

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

+4
source share
3 answers

I don’t know how much I know. If you are sure that 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 last expression is based on the fact that substring-before() returns an empty string when the search string is not found. Thus, it will work correctly with prefix and unsigned names.

+8
source

Generally speaking, if you need an element prefix, you are doing it wrong. You should only be interested in which namespace it belongs to.

In your comment, you will notice that the API you are talking to requires a namespace and a namespace prefix. This is true, but the API you are attached to does not really care about the namespace prefix - in fact, it will generate a namespace prefix randomly if you do not provide it.

If you create whole XML documents, it’s good if you have a one-to-one mapping of prefixes to namespace URIs; this makes understanding the conclusion easier. But it really doesn't matter what the prefixes are.

+2
source

For further nuances, I recommend reading The Dangers of the name () Function .

For example, only in XPath 2.0 can you reliably get the element prefix. 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"/> 

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

+1
source

All Articles