New to XSLT - how to return text of span class in

2019-08-01 06:38发布

I have the following XML:

    <core:renderedItem>
    <span class="harvard_title">Whose Ecosystem is it Anyway: Private and Public Rights under New Approaches to Biodiversity Conservation</span>
    '
    <span>
      <em>Journal of Human Rights and the Environment</em>
    </span>
    .
  </div>

How do I get access to the text of span class="harvard_title" using xslt? Ideally I would like to return just the text up to the colon "Whose Ecosystem is it Anyway"

标签: xml xslt html
1条回答
疯言疯语
2楼-- · 2019-08-01 07:03

Assuming this xml (the one you posted is not well formed):

<div xmlns:core="http://www.w3.org/core">
    <core:renderedItem>
        <span class="harvard_title">Whose Ecosystem is it Anyway: Private and Public Rights under New Approaches to Biodiversity Conservation</span>
        '
        <span>
            <em>Journal of Human Rights and the Environment</em>
        </span>
        .
    </core:renderedItem>
</div>

You can get the text you want with this xsl code:

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:core="http://www.w3.org/core"
  exclude-result-prefixes="xsl">
  <xsl:output omit-xml-declaration="yes" method="xml" indent="yes" />

  <xsl:template match="/">
    <xsl:value-of select="substring-before(div/core:renderedItem/span[@class = 'harvard_title'], ':')" />
  </xsl:template>

</xsl:stylesheet>

Whith this: span[@class = 'harvard_title'] you get the text inside the span, and with substring-before function you get just the text before de colon.

Hope it helps.

Edit: you can use an if to take into account the case where there is not a colon in the text, but you can do it using templates:

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:core="http://www.w3.org/core"
  exclude-result-prefixes="xsl">
  <xsl:output omit-xml-declaration="yes" method="xml" indent="yes" />

  <xsl:template match="/">
    <xsl:apply-templates select="div/core:renderedItem/span[@class = 'harvard_title']" />
  </xsl:template>

  <!-- generic template, for span elements with class = 'harvard_title' -->
  <xsl:template match="span[@class = 'harvard_title']">
    <xsl:value-of select="." />
  </xsl:template>
  <!-- more specific template, for those ones containing a colon -->
  <xsl:template match="span[@class = 'harvard_title'][contains(.,':')]">
    <xsl:value-of select="substring-before(., ':')" />
  </xsl:template>

</xsl:stylesheet>
查看更多
登录 后发表回答