使用XSLT转换XML时遇输出换行问题,附相关代码
解决XSLT转换XML时输出内容换行的问题
嘿,我看你在用XSLT处理XML的时候碰到输出莫名换行的问题了!先把你提供的代码整理出来(看起来@pos='VV...'这部分没写完,不过先基于现有内容分析):
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="1.0"> <xsl:template match="/" > <data> <content> <xsl:for-each select="//t[@pos='ADV' or @pos='ADJD' or @pos='ADJA' or @pos='NE' or @pos='NN' or @pos='VMFIN' or @pos='VVINF' or @pos='VAFIN' or @pos='VV...']"> <!-- 这里应该是你输出内容的逻辑 --> </xsl:for-each> </content> </data> </xsl:template> </xsl:stylesheet>
常见的换行原因&解决办法
源XML的空白节点干扰:XSLT默认会保留XML里的换行、空格这些空白节点,当你遍历
<t>元素时,这些空白可能被一起输出,导致莫名换行。
解决:在样式表开头加上<xsl:strip-space elements="*"/>,直接去掉所有元素的空白节点;如果某些元素需要保留空白,再用<xsl:preserve-space elements="需要保留的元素名"/>单独指定。循环输出时的自动换行:如果你的循环里每次输出
<t>的内容时,没有控制空白,XSLT可能会因为节点结构自动添加换行。
解决:用<xsl:value-of select="."/>直接输出文本,搭配<xsl:text>来手动控制分隔符(比如空格),避免自动换行。比如:<xsl:for-each select="//t[@pos='ADV' or ...]"> <xsl:value-of select="."/> <xsl:text> </xsl:text> <!-- 用空格分隔,而不是换行 --> </xsl:for-each>输出序列化的默认缩进:如果你的输出是XML/HTML,XSLT默认会开启缩进,这也会带来额外的换行。
解决:添加<xsl:output>标签关闭缩进:<xsl:output method="xml" indent="no" encoding="UTF-8"/>文本内容自带换行:如果
<t>元素的文本本身就含有换行符,那输出自然会换行。
解决:用normalize-space()函数清理文本里的多余空白和换行,比如<xsl:value-of select="normalize-space(.)"/>。
修改后的示例代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="1.0"> <!-- 去掉所有元素的空白节点 --> <xsl:strip-space elements="*"/> <!-- 关闭输出缩进,避免自动换行 --> <xsl:output method="xml" indent="no" encoding="UTF-8"/> <xsl:template match="/" > <data> <content> <xsl:for-each select="//t[@pos='ADV' or @pos='ADJD' or @pos='ADJA' or @pos='NE' or @pos='NN' or @pos='VMFIN' or @pos='VVINF' or @pos='VAFIN' or @pos='VV...']"> <!-- 清理文本并输出,用空格分隔 --> <xsl:value-of select="normalize-space(.)"/> <xsl:text> </xsl:text> </xsl:for-each> </content> </data> </xsl:template> </xsl:stylesheet>
记得把代码里的@pos='VV...'补全成完整的选择器哦!
内容的提问来源于stack exchange,提问作者Sivert Ekse
相关产品推荐
相关产品推荐

