由换行符分隔的XML文档

问题描述 投票:0回答:1
I need to be able to output the text of an XML document separated by line breaks

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

<ShortNote> <CatchWord> <HiddenData>刑法 - </ HiddenData>警察</ CatchWord> - <CatchWord> <HiddenData>任命敏感帖子 - </ HiddenData>警察总监(DGP)</ CatchWord> </ ShortNote>

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>
xslt-1.0 xslt-2.0
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.