XML文档以换行符分隔

时间:2019-04-20 09:07:03

标签: xslt-1.0 xslt-2.0

I need to be able to output the text of an XML document separated by line breaks

请检查我的代码有什么问题     xml:-

刑法— 警察 任命敏感职位— 警察局长(DGP)

Need output following
<ShortNote>
<SNHeading1>Criminal Law</SNHeading1>
<SNHeading2>Police</SNHeading2>
<SNHeading3>#Appointment to Sensitive Posts</SNHeading3>
<SNHeading4>Director General of Police (DGP)</SNHeading4>
</ShortNote>

following code use but not output according to me:-
<xsl:template match="ShortNote/CatchWord">
    <xsl:param name="text" select="normalize-space(.)"/>
            <xsl:if test="normalize-space(substring-before(concat($text,'&#8212;'),'&#8212;'))!=''">
    <xsl:element name="SNHeading{position()}">
        <xsl:value-of select="normalize-space(substring-before(concat($text,'&#8212;'),'&#8212;'))"/>
    </xsl:element>
    </xsl:if>
    <xsl:if test="contains($text,'&#8212;')">
        <xsl:message><xsl:value-of select="."/></xsl:message>
        <xsl:element name="SNHeading{position()+1}">
        <xsl:apply-templates select=".">
            <xsl:with-param name="text" select="substring-after($text,'&#8212;')"/>
        </xsl:apply-templates>
        </xsl:element>
    </xsl:if>
</xsl:template>

1 个答案:

答案 0 :(得分:1)

假设至少使用XSLT 2.0,我认为您可以简单地处理CatchWord/tokenize(., '—'),例如在XSLT 3中

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:output indent="yes"/>

  <xsl:template match="ShortNote">
      <xsl:copy>
         <xsl:apply-templates select="CatchWord!tokenize(., '—')!normalize-space()"/> 
      </xsl:copy>
  </xsl:template>

  <xsl:template match=".[. instance of xs:string]" expand-text="yes">
      <xsl:element name="SNHeading{position()}">{.}</xsl:element>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/bFN1y9u

对于无法匹配字符串的XSLT 2,可以使用xsl:for-each

  <xsl:template match="ShortNote">
      <xsl:copy>
         <xsl:for-each select="for $s in CatchWord/tokenize(., '—') return normalize-space($s)">
            <xsl:element name="SNHeading{position()}">
                <xsl:value-of select="."/>
            </xsl:element>
         </xsl:for-each>
      </xsl:copy>
  </xsl:template>

https://xsltfiddle.liberty-development.net/bFN1y9u/1