1

I made a simple example of xslt. I want to show tag name in h2. How to show the tag name using xslt?

Here is my code: Link

I used this

<!--h1><xsl:value-of select="abc/p/name(.)"/></h1-->

It gives me an error. Why?

Expected output:

"P" (first tag inside abc tag)

user944513
  • 12,247
  • 49
  • 168
  • 318

2 Answers2

1

Your attempt:

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

will work, provided your processor supports XSLT 2.0.

In XSLT 1.0, you need to do:

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

which will also work in XSLT 2.0, of course.

michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
0

First of all: add a <xsl:template match="text()" /> to avoid unwanted output.

Then I would change the first template to match you abc because this is the interesting parent node. If you want any child of the node, use abc/*. Then the template will match abs/p and abc/catalog. But you only want the first child, right? So use abc/*[1]. This will only match abc/p. And now you can do the name(.) or local-name().

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

  <xsl:template match="abc/*[1]">
    <html>
      <body>
       <h1><xsl:value-of select="local-name()"/></h1>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="text()" />

</xsl:stylesheet>

Your XML-File

<abc>
    <p test='ravi'>test123</p>
    <catalog>
        <cd>
            <title>Empire Burlesque</title>
            <artist>Bob Dylan</artist>
            <country>USA</country>
            <company>Columbia</company>
            <price>10.90</price>
            <year>1985</year>
        </cd>
    </catalog>
</abc>

Read this: https://stackoverflow.com/a/585290/5413817

Community
  • 1
  • 1
Marcus
  • 1,910
  • 2
  • 16
  • 27