XML/XSL Replacing a space with

2019-07-11 11:15发布

I'm trying to clean up the readability of my code. Using v1. Any help on what I'm doing wrong is greatly appreciated.

XML code that I have:

    ...
    <trusted-servers>mark mike sally</trusted-servers>
    ...

I want it to display the following way:

    mark
    mike
    sally

Originally, it's displaying in this way using (<xsl:value-of select="trusted-servers"/>):

    mark mike sally

What I have tried is:

    <xsl:value-of select="string-length(substring-before(trusted-servers, concat(' ', trusted-servers, '<xsl:text disable-output-escaping="yes"><![CDATA[<br />]]></xsl:text>')))" data-type="string"/>

But it throws an error saying that unescaped character < isn't allowed. I tried taking out the <xsl:text disable-output-escaping="yes"><![CDATA[<br />]]></xsl:text> part and replacing it with <br/> but still have the same error. I'm clueless in any other ways of doing it.

标签: xml xslt
2条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-11 11:39

Assuming xsltproc you have http://exslt.org/str/functions/tokenize/index.html so you can do

<xsl:template match="trusted-servers">
  <xsl:for-each select="str:tokenize(., ' ')">
    <xsl:if test="position() > 1"><br/></xsl:if>
    <xsl:value-of select="."/>
  </xsl:for-each>
</xsl:template>

where you declare xmlns:str="http://exslt.org/strings" on the xsl:stylesheet.

查看更多
做个烂人
3楼-- · 2019-07-11 11:54

Generally speaking, <xsl:text disable-output-escaping="yes">should be avoided as much as possible!

Since you're using XSLT 1.0, the best solution is to write a template which will recursively replace the first space encountered by a <br>, for instance:

<xsl:template match="trusted-servers" name="replace-space-by-br">
    <xsl:param name="text" select="."/>
    <xsl:choose>
        <xsl:when test="contains($text, ' ')">
            <xsl:variable name="head" select="substring-before($text, ' ')"/>
            <xsl:variable name="tail" select="substring-after($text, ' ')"/>
            <xsl:value-of select="$head"/>
            <br/>
            <xsl:call-template name="replace-space-by-br">
                <xsl:with-param name="text" select="$tail"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
查看更多
登录 后发表回答