xml – XSLT – 使用XPath计运算符元素的数量
发布时间:2020-12-16 07:43:11 所属栏目:百科 来源:网络整理
导读:我有以下 XML文件存储电影和演员细节: databasexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="movies.xsd"movies movie movieID="1" titleMovie 1/title actors actor actorID="1" nameBob/name age32/age height1
我有以下
XML文件存储电影和演员细节:
<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> 如果actor元素包含多个子元素(在这种情况下它是名称,年龄和高度),那么我想显示其名称 但是,如果actor元素只包含一个子元素(name),则应该以纯文本形式显示. XSLT: <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:choose> <xsl:when test="actor[count(*) > 1]/name"> <a href="actor_details.php?actorID={@actorID}"> <xsl:value-of select="name"/> </a> <br/> </xsl:when> <xsl:otherwise> <xsl:value-of select="name"/> <br/> </xsl:otherwise> </xsl:choose> </xsl:template> 所以在这种情况下,Bob应该显示为一个超链接,而Mike应该显示为纯文本.但是,我的页面同时显示
你的第一个xsl:在这里测试不正确
<xsl:when test="actor[count(*) > 1]/name"> 你已经定位在这里的actor元素上,所以这将会寻找一个actor元素,它是当前actor元素的子代,并且没有发现任何东西. 你可能只是想这样做 <xsl:when test="count(*) > 1"> 或者,您可以这样做 <xsl:when test="*[2]"> 即,在第二个位置有一个元素(当您只想要检查有多个元素时,会保存所有元素的计数), 或者也许你想检查当前的actor元素是否有除名字之外的元素? <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处理器应该首先匹配更具体的模板. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |