【问题标题】:Dealing with whitespace and linebreaks in XSLT 1在 XSLT 1 中处理空格和换行符
【发布时间】:2017-09-13 15:02:28
【问题描述】:

我需要找到一种方法来处理以下 XML 中的空格和换行符:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<Message.body>
<Text>This is
    an attachment text
    with whitespaces and linebreaks
    File name: https://somerandomurl.com/123.txt
    File Type: txt
</Text>
</Message.body>

这是 XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="/">
<root>
    <xsl:choose>
            <xsl:when test="(starts-with(Message.body/Text, 'This is an attachment link:'))" />
        <xsl:otherwise>
            xxx
        </xsl:otherwise>
   </xsl:choose>
   <Name>
        <xsl:value-of select="substring-before(substring-after(Message.body/Text, 'File Name: '), 'File Type: ')"/>
   </Name>
   <Type>
        <xsl:value-of select="substring-after(Message.body/Text, 'File Type: ')"/>
   </Type>
</root>

这部分:

<xsl:when test="(starts-with(Message.body/Text, 'This is an attachment link:'))" />

当然不起作用,因为换行符之间有空格。此外,由于提到的问题,以下几行没有达到预期的结果:

实际结果:

<Name>https://somerandomurl.com/123.txt
    </Name>
<Type>txt
  </Type>

想要的结果:

<Name>https://somerandomurl.com/123.txt</Name>
<Type>txt</Type>

我应该尝试用空格替换所有换行符,还是使用 XSLT 1 有更简单的方法?

提前致谢!

【问题讨论】:

    标签: xml xslt-1.0 whitespace line-breaks


    【解决方案1】:

    您应该可以使用normalize-space() 来解决这两个问题...

    <xsl:template match="/">
      <root>
        <xsl:choose>
          <xsl:when test="starts-with(normalize-space(Message.body/Text), 'This is an attachment link:')" />
          <xsl:otherwise>
            xxx
          </xsl:otherwise>
        </xsl:choose>
        <Name>
          <xsl:value-of select="normalize-space(substring-before(substring-after(normalize-space(Message.body/Text), 'File name: '), 'File Type: '))"/>
        </Name>
        <Type>
          <xsl:value-of select="normalize-space(substring-after(Message.body/Text, 'File Type: '))"/>
        </Type>
      </root>
    </xsl:template>
    

    请注意,substring-after 和 substring-before 中的字符串比较区分大小写,因此我必须将 File Name: 更改为 File name: 以匹配您的输入。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 2021-09-19
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多