62

I don't really understand the difference between the XPath functions name and local-name.

Could you give an example of a situation where they would differ?

Edit

Given this example:

<?xml version="1.0" ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head></head>
</html>

I get the same result with these two queries: //*[local-name()="head"] and //*[name()="head"]. Why is that?

troelskn
  • 115,121
  • 27
  • 131
  • 155

1 Answers1

86

With the XML being

<x:html xmlns:x="http://www.w3.org/1999/xhtml"/>

the stylesheet

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output indent="yes"/>

  <xsl:template match="*">
    <local-name><xsl:value-of select="local-name()"/></local-name>
    <name><xsl:value-of select="name()"/></name>
  </xsl:template>

</xsl:stylesheet>

outputs

<local-name>html</local-name>
<name>x:html</name>

So the local-name() result is without any prefix, the name() result might include a prefix.

In your sample with a default namespace declaration no prefix is present, therefore name() and local-name() give the same result.

gioele
  • 9,748
  • 5
  • 55
  • 80
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • If your stylesheet includes the xhtml namespace with different prefix, name() outputs the prefix in input XML. What if I want the prefix to be the one defined in the stylesheet? – Lingamurthy CS Feb 16 '14 at 05:45
  • There are namespace nodes on the namespace axis and in XSLT/XPath 2.0 there are functions to operate on and resolve namespaces or find prefixes like http://www.w3.org/TR/xpath-functions/#func-in-scope-prefixes which of course can be applied to nodes in the stylesheet as well. You can get hold of the document node of your stylesheet using `document('')`. Ask a question on your own if you need more explanation on that. – Martin Honnen Feb 16 '14 at 10:11
  • Hi, I've asked a question on this: http://stackoverflow.com/questions/21811344/how-to-get-namespace-prefix-as-defined-in-stylesheet-and-not-from-input-xml – Lingamurthy CS Feb 16 '14 at 12:52