我们使用 xslt 将接口中的 xml 接口转换成 html 结构的数据输出到页面中,这里也简单的总结一下,方便后续的使用。 有时候会出现这种情况:有很多并列的节点 这里我们能使用 位置路径表达式 这里有个模板 C,模板 A 和模板 B 都会调用它,但是逻辑上或其他地方只有一点点的区别,也没必要写一个新的模板,只需用一个参数区分即可。 在用 xslt 将 xml 转换为 html 时,经常会给标签添加属性值,比如 a 标签的 都是可以的。 对 xslt 不太熟悉,这也是工作过程中总结出来的,在接下来的工作中,还会有更多的总结。1. 使用子节点的值进行过滤 #
item
,但是只能根据这个 item 节点里面的节点art_type
来过滤出这些item
节点来。比如 art_type
有 0 和 1 两个值,我现在只想要 art_type 值为 1 的item
节点:<xsl:for-each select="item/art_type[text()=1]/parent::*">
<xsl:if test="position() >= 1 and position() <= 3">
<xsl:call-template name="one">xsl:call-template>
xsl:if>
xsl:for-each>
parent
关键词回到上一个节点。
轴名称
结果
ancestor
选取当前节点的所有先辈(父、祖父等)。
ancestor-or-self
选取当前节点的所有先辈(父、祖父等)以及当前节点本身。
attribute
选取当前节点的所有属性。
child
选取当前节点的所有子元素。
descendant
选取当前节点的所有后代元素(子、孙等)。
descendant-or-self
选取当前节点的所有后代元素(子、孙等)以及当前节点本身。
following
选取文档中当前节点的结束标签之后的所有节点。
namespace
选取当前节点的所有命名空间节点。
parent
选取当前节点的父节点。
preceding
选取文档中当前节点的开始标签之前的所有节点。
preceding-sibling
选取当前节点之前的所有同级节点。
self
选取当前节点。
例子
结果
child::book
选取所有属于当前节点的子元素的 book 节点。
attribute::lang
选取当前节点的 lang 属性。
child::*
选取当前节点的所有子元素。
attribute::*
选取当前节点的所有属性。
child::text()
选取当前节点的所有文本子节点。
child::node()
选取当前节点的所有子节点。
descendant::book
选取当前节点的所有 book 后代。
ancestor::book
选择当前节点的所有 book 先辈。
ancestor-or-self::book
选取当前节点的所有 book 先辈以及当前节点(如果此节点是 book 节点)
child::*/child::price
选取当前节点的所有 price 孙节点。
2. 将参数传递给另一个模板 #
"1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="gb2312" indent="yes"/>
<xsl:template match="/root">
<xsl:call-template name="one_list">
<xsl:with-param name="page_name">xiaomingxsl:with-param>
xsl:call-template>
<xsl:call-template name="one_list">
<xsl:with-param name="page_name">xiaohongxsl:with-param>
xsl:call-template>
xsl:template>
<xsl:template name="one_list">
<xsl:param name="page_name" />
<xsl:if test="$page_name = 'xiaoming'">
<p>hello xiaomingp>
xsl:if>
xsl:template>
xsl:stylesheet>
3. 渲染模板为节点添加属性 #
href
,img 标签的src
等。通常有两种方式都可以。<a target="_blank" class="pic">
<xsl:attribute name="href">
<xsl:value-of select="url" />
xsl:attribute>
a>
<a href="{url}" target="_blank" class="pic">a>
4. 检测某个节点存在且不为空 #
<xsl:choose>
<xsl:when test="count(mimgs) > 0 and string-length(mimgs/imgurl32) > 0 ">
<xsl:value-of select="mimgs/imgurl32"/>
xsl:when>
<xsl:otherwise>
<xsl:value-of select="img"/>
xsl:otherwise>
xsl:choose>
5. 总结 #
版权属于:
加速器之家
作品采用:
《
署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
》许可协议授权
评论