Wrap two nodes with values greater than 0 with a d

2019-07-20 05:41发布

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

标签: xslt xpath
1条回答
够拽才男人
2楼-- · 2019-07-20 06:16

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.

查看更多
登录 后发表回答