You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XSLT文本输出空白控制:xsltproc输出CDATA无周边空白方法

xsltproc处理XSLT时输出无多余空白文本的解决方案

问题说明

使用xsltproc工具处理XSLT时,所用的格式化程序会默认在CDATA段前后插入空格,需要输出无周边多余空白的CDATA内容。没有强制使用xsl:text的要求,也尝试过xsl:value-of,但不清楚如何在xsl:value-of中使用CDATA,手动删除CDATA周边空格后,格式化程序会自动将空格加回。

错误示例代码

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="UTF-8" indent='no' />
    <xsl:strip-space elements="*" />

    <xsl:template match="/">
        <xsl:text>
            <![CDATA[/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
]]>
        </xsl:text>
        <xsl:text>
            <![CDATA[/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
]]>
        </xsl:text>
    </xsl:template>

</xsl:stylesheet>

实际输出结果

jonsmirl@ares:~/aosp/blogs/jonsmirl.github.io/xml$ xsltproc test.xsl test.xsl

            /*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/

        
            /*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/

        jonsmirl@ares:~/aosp/blogs/jonsmirl.github.io/xml$ 

期望输出结果

jonsmirl@ares:~/aosp/blogs/jonsmirl.github.io/xml$ xsltproc test.xsl test.xsl
/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
jonsmirl@ares:~/aosp/blogs/jonsmirl.github.io/xml$ 

可行解决方案

此前误以为必须将文本放在CDATA中才能避免格式化程序修改,实际去掉CDATA、直接在xsl:text中写入对应文本即可实现期望效果。

正确代码示例

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="UTF-8" indent='no' />
    <xsl:strip-space elements="*" />

    <xsl:template match="/">
        <xsl:text>/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
</xsl:text>
        <xsl:text>/*
*    Licensed under the Apache License, Version 2.0 (the "License");
*/
</xsl:text>
    </xsl:template>

</xsl:stylesheet>

内容的提问来源于stack exchange,提问作者Jon Smirl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:45:02