1

Am trying to use XSLT for my XML given below -

<?xml version="1.0" encoding="UTF-8"?>
<a:catalog>
<a:cd>
    <a:title>Empire Burlesque</a:title>
    <a:artist>Bob Dylan</a:artist>
    <a:country>USA</a:country>

</a:cd>
<a:cd>
    <a:title>Hide your heart</a:title>
    <a:artist>Bonnie Tyler</a:artist>
    <a:country>UK</a:country>
</a:cd>
</a:catalog>

And below id my XSLT which am trying to run to fetch a:title and a:artist

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html> 
<body>
  <h2>My test XSLT</h2>
  <table border="1">
    <tr bgcolor="#9acd32">
      <th style="text-align:left">Title</th>
      <th style="text-align:left">Artist</th>
    </tr>
    <xsl:for-each select="a:catalog/a:cd">
    <tr>
      <td><xsl:value-of select="a:title"/></td>
      <td><xsl:value-of select="a:artist"/></td>
    </tr>
    </xsl:for-each>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

In this without namespace I can get output but not with namespace. Or should I write code for remove namespaces from XML ?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
V.Rohan
  • 945
  • 2
  • 14
  • 27
  • 1
    You need to map the namespace prefixed with `a` in the XSL also. The XML that you have shared does not show any namespace. – Aniket V Mar 22 '18 at 12:12

1 Answers1

1

Both your XML and your XSLT have to declare all namespaces in use.

(No, do not write code to remove the namespaces. Namespaces play a valuable role in XML vocabulary definition and management.)

Instead, add a namespace declaration, such as

xmlns:a="http://example.com/a"

to the root elements in your XML and XSLT files.

Note that to use a namespace prefix in an XML document without defining it prevents the XML document from being namespace-well-formed.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Yes, @kjhughes, this worked for me.One more related question that if i have same xml format with different nested namespaces like below then ? __ Empire Burlesque Hide your heart __ – V.Rohan Mar 22 '18 at 13:21
  • 1
    All used namespace prefixes must be declared as shown in this answer. Note that it is the binding to a namespace URI that gives the prefix its meaning, not the prefix itself. This means that if `a0` and `a1` are both bound to `http://example.com/a`, then `a0:x` and `a1:x` are the same names. – kjhughes Mar 22 '18 at 13:29
  • Is this i have to add in xsl root elements for __xmlns:a2=" http://example.com/a2" xmlns:a0=" http://example.com/a0" xmlns:a1=" http://example.com/a1"__ – V.Rohan Mar 22 '18 at 13:54
  • And in your XML too, yes. – kjhughes Mar 22 '18 at 13:55
  • Thank you for solution and provided info for XML Document "namespace-well-formed" – V.Rohan Mar 22 '18 at 14:45