XSLT comma separation for sublist of list

2019-08-14 03:27发布

How to do with XSLT from this

<lines>
  <data>
    a
  </data>
  <data>
    b
  </data>
  <data>
    a
  </data>
  <data>
    b
  </data>
  <data>
    c
  </data>
  <data>
    b
  </data>
  <data>
    c
  </data>
</lines>

this

<resultdata>
  b,b,b
</resultdata>

As far as i understand i shal use

<xsl:for-each select="/data"> 

and

<xsl:if test="data(text)='b'">

and

<xsl:text>, </xsl:text>

But how exactly?

标签: xml xslt
1条回答
别忘想泡老子
2楼-- · 2019-08-14 04:21

Instead of doing this...

 <xsl:for-each select="/data"> 

You need to do this...

<xsl:for-each select="/lines/data"> 

This is because the initial / represents the document node, which is the parent node of lines. However, it would actually be better if you were positioned on the lines element at the time (by being in a template that matched lines). Then you could just do this (because without the preceding / the expression is then relative to the current node).

<xsl:for-each select="data"> 

To check the text of the node, you need to do this:

<xsl:if test="text()='b'">

Or rather, because you have white-space, you should be doing this:

<xsl:if test="normalize-space()='b'">

Or better still, you add the condition to the xsl:for-each itself.

<xsl:for-each select="data[normalize-space() = 'b']">

Try this XSLT to start you going:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />

    <xsl:template match="lines">
        <resultdata>
            <xsl:for-each select="data[normalize-space() = 'b']">
                <xsl:if test="position() > 1">
                    <xsl:text>, </xsl:text>
                </xsl:if>
                <xsl:value-of select="normalize-space()" />
            </xsl:for-each>
        </resultdata>
    </xsl:template>
</xsl:stylesheet>
查看更多
登录 后发表回答