gpt4 book ai didi

xml - XSLT - 使用 XPath 计算子元素的数量

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:31 25 4
gpt4 key购买 nike

我有以下存储电影和 Actor 详细信息的 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 元素只包含一个子元素(名称),那么它应该显示为纯文本。

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(*) &gt; 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 应该显示为纯文本。但是,我的页面同时显示Bob 和 Mike 为纯文本。

最佳答案

您的第一个 xsl:when 测试在这里不正确

<xsl:when test="actor[count(*) &gt; 1]/name">

您已经在此处的 actor 元素上定位,因此这将寻找作为当前 actor 子元素的 actor 元素> 元素,但什么也没找到。

你可能只想这样做

<xsl:when test="count(*) &gt; 1">

或者,你可以这样做

<xsl:when test="*[2]">

即,第二个位置是否有一个元素(当您真的只想检查是否有多个元素时,可以节省对所有元素的计数),

或者您可能想检查当前的 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 处理器应首先匹配更具体的模板。

关于xml - XSLT - 使用 XPath 计算子元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com