Xml XSLT-使用XPath计算子元素的数量
我有以下存储电影和演员详细信息的XML文件:Xml XSLT-使用XPath计算子元素的数量,xml,xslt,xpath,count,Xml,Xslt,Xpath,Count,我有以下存储电影和演员详细信息的XML文件: <database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="movies.xsd"> <movies> <movie movieID="1"> <title>Movie 1</title> <actors>
<database
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="movies.xsd">
<movies>
<movie movieID="1">
<title>Movie 1</title>
<actors>
<actor actorID="1">
<name>Bob</name>
<age>32</age>
<height>182 cm</height>
</actor>
<actor actorID="2">
<name>Mike</name>
</actor>
</actors>
</movie>
</movies>
</database>
因此,在本例中,Bob应显示为超链接,Mike应显示为纯文本。但是,我的页面同时显示
Bob和Mike作为纯文本。您的第一个xsl:when测试在这里不正确
<xsl:when test="actor[count(*) > 1]/name">
您已经定位在这里的actor元素上,因此这将查找作为当前actor元素的子元素的actor元素,但什么也找不到
你可能只是想这么做
<xsl:when test="count(*) > 1">
或者,您也可以这样做
<xsl:when test="*[2]">
i、 e,第二个位置是否有一个元素(当您只想检查有多个元素时,可以保存对所有元素的计数)
或者,您可能希望检查当前的actor元素是否具有除name之外的元素
<xsl:when test="*[not(self::name)]">
另外,最好将测试放在模板匹配中,而不是使用xsl:choose
试试这个XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no"/>
<xsl:template match="/">
<div>
<xsl:apply-templates select="database/movies/movie"/>
</div>
</xsl:template>
<xsl:template match="movie">
<xsl:value-of select="concat('Title: ', title)"/>
<br/>
<xsl:text>Actors: </xsl:text>
<xsl:apply-templates select="actors/actor"/>
<br/>
</xsl:template>
<xsl:template match="actor">
<xsl:value-of select="name"/>
<br/>
</xsl:template>
<xsl:template match="actor[*[2]]">
<a href="actor_details.php?actorID={@actorID}">
<xsl:value-of select="name"/>
</a>
<br/>
</xsl:template>
</xsl:stylesheet>
演员:
请注意,在此实例中,XSLT处理器应首先匹配更具体的模板
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8" omit-xml-declaration="no"/>
<xsl:template match="/">
<div>
<xsl:apply-templates select="database/movies/movie"/>
</div>
</xsl:template>
<xsl:template match="movie">
<xsl:value-of select="concat('Title: ', title)"/>
<br/>
<xsl:text>Actors: </xsl:text>
<xsl:apply-templates select="actors/actor"/>
<br/>
</xsl:template>
<xsl:template match="actor">
<xsl:value-of select="name"/>
<br/>
</xsl:template>
<xsl:template match="actor[*[2]]">
<a href="actor_details.php?actorID={@actorID}">
<xsl:value-of select="name"/>
</a>
<br/>
</xsl:template>
</xsl:stylesheet>