How do I replace sequences of whitespaces by one space but don't trim in XSLT?

后端 未结 2 1288
独厮守ぢ
独厮守ぢ 2021-01-03 02:04

The function normalize-space removes leading and trailing whitespace and replaces sequences of whitespace characters by a single space. How can I only

相关标签:
2条回答
  • 2021-01-03 02:10

    Use this XPath 1.0 expression:

    concat(substring(' ', 1 + not(substring(.,1,1)=' ')), 
           normalize-space(), 
           substring(' ', 1 + not(substring(., string-length(.)) = ' '))
          )
    

    To verify this, the following transformation:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
     </xsl:template>
    
     <xsl:template match="text()">
      <xsl:value-of select=
      "concat(substring(' ', 1 + not(substring(.,1,1)=' ')),
              normalize-space(),
              substring(' ', 1 + not(substring(., string-length(.)) = ' '))
              )
      "/>
     </xsl:template>
    </xsl:stylesheet>
    

    when applied on this XML document:

    <t>
     <t1>   xxx   yyy   zzz   </t1>
     <t2>xxx   yyy   zzz</t2>
     <t3>  xxx   yyy   zzz</t3>
     <t4>xxx   yyy   zzz  </t4>
    </t>
    

    produces the wanted, correct result:

    <t>
       <t1> xxx yyy zzz </t1>
       <t2>xxx yyy zzz</t2>
       <t3> xxx yyy zzz</t3>
       <t4>xxx yyy zzz </t4>
    </t>
    
    0 讨论(0)
  • 2021-01-03 02:31

    Without Becker's method, you could use some discouraged character as mark:

    translate(normalize-space(concat('&#x7F;',.,'&#x7F;')),'&#x7F;','')
    

    Note: Three function calls...

    Or with any character but repeating some expression:

    substring(
       normalize-space(concat('.',.,'.')),
       2,
       string-length(normalize-space(concat('.',.,'.'))) - 2
    )
    

    In XSLT you can easily declare a variable:

    <xsl:variable name="vNormalize" select="normalize-space(concat('.',.,'.'))"/>
    <xsl:value-of select="susbtring($vNormalize,2,string-length($vNormalize)-2)"/>
    
    0 讨论(0)
提交回复
热议问题