XML Document not registering XSL stylesheet?

2019-03-04 19:38发布

问题:

I've been trying to test-link my XML document with my XSL stylesheet, however it all it does is display the XML doc's information and ignores my templates, and I have no clue why.

movies.xml document

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="movies.xsl"?>

<movieRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.example.com/comicbooks/movies/ns"
       xsi:schemaLocation="http://www.example.com/comicbooks/movies/ns movies.xsd"> 

    <movie>

        <movieTitle>Captain America: Civil War</movieTitle>
        <genre>Action, Adventure, Sci-Fi</genre>
        <rating>8.13</rating>
        <length>147 min</length>
        <releaseDate>May 6th, 2016</releaseDate>

    </movie>

</movieRoot>

movies.xsl stylesheet (I've also tried apply-templates select="movies" as well)

<?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>
        <link ref="stylesheet" type="text/css" href="movies.css" />
        <body>
            <xsl:apply-templates />

        </body>
        </html>


    </xsl:template>

    <xsl:template match="movie">

        <p>Movies</p>

    </xsl:template>

</xsl:stylesheet>

movies.css

body {color:blue;}

回答1:

Your xml file has a default namespace.
You need to declare this namespace in the xsl file and use it.

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ns="http://www.example.com/comicbooks/movies/ns">


<xsl:template match="ns:movie">

Also you have a typo: ref instead of rel.

<link rel="stylesheet" type="text/css" href="movies.css" />

After modifying the xsl file should look like this:

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

    <xsl:template match="/">

        <html>
        <link rel="stylesheet" type="text/css" href="movies.css" />
        <body>
            <xsl:apply-templates />
        </body>
        </html>

    </xsl:template>

    <xsl:template match="ns:movie">

        <p>Movies</p>

    </xsl:template>

</xsl:stylesheet>

Other files remain unchanged.



标签: xml xslt