又上了名字空间的套

在做一个XML的XSL,原XML如下:

<?xml version="1.0" encoding="utf-16"?>
<book version="5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns="http://docbook.org/ns/docbook">
  <info>
    <title>test</title>
    <author>
      <personname>
        <othername>Unknown</othername>
      </personname>
    </author>
    <bibliosource>Unknown</bibliosource>
  </info>
</book>

制作的XSL:

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

    <xsl:template match="info">
        <xsl:value-of select="title" />
    </xsl:template>       
    <xsl:template match="/">
        <xsl:apply-templates select="/book/info" />
    </xsl:template>
</xsl:stylesheet>

结果是没有任何输出,郁闷了好久才发现是因为忽略名字空间造成的,注意在XML中定义了xmlns,而在XSL中没有对应的定义,导致XPath无法正确地找到节点。解决的办法很简单,只要在XSL中加入缺省定义就可以了,如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://docbook.org/ns/docbook">

早先在使用XSL生成XHTML的时候,也有过一次因为名字空间冲突导致无法输出的问题,看来名字空间这个东西真不是个善茬,要时时刻刻得小心谨慎阿

Leave a Reply

Your email address will not be published. Required fields are marked *