XSLT document('') function doesn't wor

2019-01-26 16:06发布

问题:

As I understand from docs, XSLT function document() with empty string as parameter should read current XSLT document. But the following code doesn't work:

  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <state>test2</state>
   <xsl:template match="/">
      test1
      <xsl:value-of select="document('')/*/state"/>
    </xsl:template>
   </xsl:stylesheet>

When I apply this XSLT to some XML (just for example), I have only "test1" as output. Why line

 <xsl:value-of select="document('')/*/state"/>

doesn't print "test2"?

回答1:

The definition of document('') is that it reads the XML document whose URI is the same as the base URI of the instruction in the stylesheet containing the document('') call. Unless you use external entities, this is normally the same as the base URI of the stylesheet module. If it doesn't work, this is often because the base URI of the stylesheet module is unknown. This can easily happen if the XSLT processor is given a stylesheet that's in memory (for example as a character string or a DOM) rather than a resource retrieved via a URI. For example, if you use a JAXP StreamSource and don't call setSystemId() then the base URI will be unknown.



回答2:

You should declare your own namespace, like this:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:my="http://localhost"
    exclude-result-prefixes="my">
    <xsl:output method="text"/>

    <my:state>test2</my:state>

    <xsl:template match="/">
        <xsl:text>test1</xsl:text>
        <xsl:value-of select="document('')/*/my:state"/>
    </xsl:template>
</xsl:stylesheet>

Ouput:

test1test2

Quoting Michael Kay:

A user-defined top-level element must also belong to a namespace with a non-null URI, different from the XSLT namespace, and preferably different from the namespace URI used by any vendor. These elements are ignored by the XSLT processor.



标签: xml xslt