我的XSLT中有什么错误?

rgk*_*gan 1 xml xslt xpath

这是我的xml文件

<html xmlns="http://www.w3schools.com">
    <body>
        <shelf>
            <cd id="el01">
                <artist>Elton John</artist>
                <title>Circle of Life</title>
                <country>UK</country>
                <company>Spectrum</company>
                <price>10.90</price>
                <year>1999</year>
                <description>As heard in the Lion King.</description>
            </cd>

            <book id="bk101">
                <author>Gambardella, Matthew</author>
                <title>XML Developer's Guide</title>
                <genre>Computer</genre>
                <price>44.95</price>
                <publish_date>2000-10-01</publish_date>
                <description>An in-depth look at creating applications 
      with XML.
                </description>
            </book>

          </shelf>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的XSL文件

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

<!-- TODO customize transformation rules 
     syntax recommendation http://www.w3.org/TR/xslt 
-->
<xsl:template match="/">
    <html>
        <head>
            <title>The Shelf</title>
        </head>
        <body>
            <h1>The Shelf</h1>
            <xsl:apply-templates select="shelf"/>
        </body>
    </html>
</xsl:template>
<xsl:template match="//shelf">
    <xsl:for-each select="cd|book">
        <xsl:value-of select="title"/>
    </xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

我的输出只是浏览器中的"The Shelf".我哪里错了?

Mik*_*ain 6

你有两个问题.

  1. 您的数据有一个命名空间"http://www.w3schools.com",但您不能在xslt中声明并使用它 - 由于xml/xpath规范不匹配,您需要更改选择器.我已经声明了一个'data'前缀来匹配你的xml文档的默认名称空间,然后改变你所有的xpath选择来匹配.不幸的是,您不能只是一个默认命名空间,因为默认名称空间在xpath中不起作用.(或者,您可以从xml文档中删除默认命名空间,但这可能并不总是一个选项).

  2. 您的货架选择器将找不到与"/"相关的任何匹配节点.我已将您的初始应用模板更改为// data:shelf以匹配所有数据:可在文档中的任何位置找到的shelf节点.

尝试以下方法

<xsl:stylesheet xmlns:data="http://www.w3schools.com" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>

<!-- TODO customize transformation rules
 syntax recommendation http://www.w3.org/TR/xslt
-->
<xsl:template match="/">
<html>
    <head>
        <title>The Shelf</title>
    </head>
    <body>
        <h1>The Shelf</h1>
        <xsl:apply-templates select="//data:shelf"/>
    </body>
</html>
</xsl:template>
<xsl:template match="//data:shelf">
<xsl:for-each select="data:cd|data:book">
    <p><xsl:value-of select="data:title"/></p>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)