[英]Convert XML to String using XSLT
需要将XML转换为String
输入XML:
<Texts>
<text>123</text>
<text>456</text>
<text>789</text>
</Texts>
输出字符串
T1=123&T2=456&T3=789
我正在使用以下XSL:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:for-each select="Texts">
<xsl:apply-templates mode="concat" select="text" />
</xsl:for-each>
</xsl:template>
<xsl:template match="text" mode="concat">
<xsl:variable name="position" select="position()"/>
<xsl:if test="position() = 1">
<xsl:text>P($position)=</xsl:text>
</xsl:if>
<xsl:value-of select="." />
<xsl:if test="position() = last()">
<xsl:text></xsl:text>
</xsl:if>
<xsl:if test="position() = last()">
<xsl:text>&P$position=</xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
让我知道怎么了。 XML中的元素文本可以是任意数字
有时使用xsl:for-each
更容易:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:for-each select="Texts/text">
<xsl:if test="position() != 1">&</xsl:if>T<xsl:value-of select="position()" />=<xsl:value-of select="." />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:apply-templates select="Texts/text" />
</xsl:template>
<xsl:template match="text">
<xsl:value-of select="concat('P', position(), '=', .)" />
<xsl:if test="position() < last()">&</xsl:if>
</xsl:template>
</xsl:stylesheet>
输出
P1=123&P2=456&P3=789
请注意,您实际上应该在每个<text>
的值上使用URL编码,但这不是XSLT 1.0内置的(但2.0具有此功能)。
如果要处理数字值,则应该没问题,否则请寻找将URL编码功能添加到样式表中的方法。 使用外部功能扩展XSLT的方法有多种,这取决于适用于您的XSLT引擎。
最简单/最快的方法是(如果在XPath 2中):
string-join(//text / concat("T", position(), "=", .), "&")
或者,更好的是,如果您实际上需要对其进行url编码,并将其逐字放在XSLT中:
string-join(//text / concat("T", position(), "=", encode-for-uri(.)), "&")
可以在XPath 2.0(以及XSLT 2.0)中完成,如下所示:
string-join(
for $i in 1 to count(//text)
return concat('T', $i, '=', (//text)[$i]),
'&')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.