处理XSLT 1中的空格和换行符

时间:2017-09-13 15:02:29

标签: xml xslt-1.0 whitespace line-breaks

我需要找到一种方法来处理以下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更简单?

提前致谢!

1 个答案:

答案 0 :(得分: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:以匹配您的输入。

相关问题