tags:

views:

6002

answers:

4

Hi all, I'm interested in assigning the tag name of the root element in an xml document to an xslt variable. For instance, if the document looked like (minus the DTD):

<foo xmlns="http://....."&gt;
    <bar>1</bar>
</foo>

and I wanted to assign the string 'foo' to an xslt variable. Is there a way to reference that?

Thanks, Matt

+1  A: 

Figured it out. The function name() given the parameter * will return foo.

Matty
+2  A: 

Hi,

I think you want to retrieve the name of the outermost XML element. This can be done like in the following XSL sample:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

  <xsl:variable name="outermostElementName" select="name(/*)" />

  <xsl:template match="/">
    <xsl:value-of select="$outermostElementName"/>
  </xsl:template>
</xsl:stylesheet>

Please note that there is a slight difference in XPath terminology:

The top of the tree is a root node (1.0 terminology) or document node (2.0). This is what "/" refers to. It's not an element: it's the parent of the outermost element (and any comments and processing instructions that precede or follow the outermost element). The root node has no name.

See http://www.dpawson.co.uk/xsl/sect2/root.html#d9799e301

0xA3
A: 

you want local-name()

annakata
@annakata: name() and local-name() are differnt. The OP clearly wants name(). Nowhere does he say that he wants the name stripped off any namespace prefix.
Dimitre Novatchev
To be fair I mean "this will do what you want" not "only this..." and nowhere in the OP does it say he wants the namespace either. I don't know about you but in my experience local-name is what I'm interested in 90%+ of the time. namespaces are one of the reasons people hate XSLT
annakata
+1  A: 

Use the XPath name() function.

One XPath expression to obtain the name of the top (not root!) element is:

       name(/*)

The name() function returns the fully-qualified name of the node, so for an element <bar:foo/> the string "bar:foo" will be returned.

In case only the local part of the name is wanted (no prefix and ":"), then the XPath local-name() function should be used.

Dimitre Novatchev