How to automatically propagate the XMLNS attribute from on XSL template to another

偶尔善良 提交于 2019-12-12 02:33:52

问题


I'm looking for a way to have the XMLNS attribute propagate automatically from one XSL Template to another so I don't have to redeclare it each time.

Here's my situation. I'm trying to transform an XML file into an XHTML file using a XSLT file. My XML file is:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" encoding="UTF-8" href="car.xslt" version="1.0"?>
<vehicle>
  <car>
    <make>Honda</make>
    <color>blue</color>
  </car>
  <car>
    <make>Saab</make>
    <color>red</color>
  </car>
</vehicle>

My XSLT file is:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
  <table cellpadding="5" border="1">
    <tr><td>make</td><td>color</td></tr>
        <xsl:apply-templates/>
  </table>
</body>
</html>
</xsl:template>

<xsl:template match="car">
    <tr xmlns="http://www.w3.org/1999/xhtml">
      <td><xsl:value-of select="make"/></td><td><xsl:value-of select="color"/></td>
    </tr>
</xsl:template>

</xsl:stylesheet>

In the XSLT file, I would like to just be able to say:

<xsl:template match="car">
    <tr>

without having to redeclare the XMLNS. Any suggestions?


回答1:


You can make XHTML the default namespace in the stylesheet; it then applies to every template:

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



回答2:


You do not need to redeclare xmlns in the example you have given. When an non-qualified QName (i.e. one without a prefix, like car) is used in XPath, it is treated as an element in empty namespace, regardless of whether you have xmlns="..." in scope or not. So you can stick xmlns="http://www.w3.org/1999/xhtml" on your <xsl:template> element, and car won't change its meaning in XPath.



来源:https://stackoverflow.com/questions/1534670/how-to-automatically-propagate-the-xmlns-attribute-from-on-xsl-template-to-anoth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!