用 div 包裹两个值大于 0 的节点 [英] Wrap two nodes with values greater than 0 with a div

查看:27
本文介绍了用 div 包裹两个值大于 0 的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用 xslt 转换以下 xml

0<item>1</item><item>2</item><item>3</item><item>0</item><item>6</item>

进入下面的html

<i>1</i><i>2</i>

<div><i>3</i><i>6</i>

换句话说,删除值为 0 的节点,并用一个 div 包裹每 2 个节点

解决方案

我会这样做:

<xsl:param name="value" select="0"/><xsl:strip-space elements="*"/><xsl:output indent="yes"/><xsl:template match="@* | node()"><xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy></xsl:模板><xsl:template match="root"><xsl:copy><xsl:apply-templates select="item[not(.= $value)][position() mod 2 = 1]" mode="group"/></xsl:copy></xsl:模板><xsl:template match="item" mode="group"><div><xsl:apply-templates select=". | following-sibling::item[not(. = $value)][1]"/>

</xsl:模板></xsl:stylesheet>

然后输入是

<item>0</item><item>1</item><item>2</item><item>3</item><item>0</item><item>6</item></root>

你得到结果

<div><item>1</item><item>2</item>

<div><item>3</item><item>6</item>

</root>

如果您还想将 item 转换为 i 元素,只需添加模板

<我><xsl:apply-templates/></i></xsl:模板>

在样式表中.

I need to convert the following xml with xslt

<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>0</item>
<item>6</item>

into the following html

<div>
  <i>1</i> 
  <i>2</i>
</div>

<div>
  <i>3</i> 
  <i>6</i>
</div>

In other words to remove nodes with 0 value and to wrap every 2 nodes with one div

解决方案

I would do it like this:

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

<xsl:param name="value" select="0"/>

<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="root">
  <xsl:copy>
    <xsl:apply-templates select="item[not(. = $value)][position() mod 2 = 1]" mode="group"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="item" mode="group">
  <div>
    <xsl:apply-templates select=". | following-sibling::item[not(. = $value)][1]"/>
  </div>
</xsl:template>

</xsl:stylesheet>

then with the input being

<root>
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>0</item>
<item>6</item>
</root>

you get the result

<root>
   <div>
      <item>1</item>
      <item>2</item>
   </div>
   <div>
      <item>3</item>
      <item>6</item>
   </div>
</root>

If you also want to transform item to i elements simply add the template

<xsl:template match="item">
  <i>
    <xsl:apply-templates/>
  </i>
</xsl:template>

in the stylesheet.

这篇关于用 div 包裹两个值大于 0 的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆