0

需要将 XML 转换为字符串

输入 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>&amp;P$position=</xsl:text>
    </xsl:if>
</xsl:template> 

</xsl:stylesheet>

让我知道有什么问题。XML 中的元素文本可以是任意数量

4

4 回答 4

1

最简单/最快的方法是(如果您在 XPath 2 中有):

 string-join(//text / concat("T", position(), "=", .), "&")

或者更好的是,如果您确实需要对它进行 url 编码,并将其逐字放在 XSLT 中:

 string-join(//text / concat("T", position(), "=", encode-for-uri(.)), "&amp;")
于 2013-10-17T00:25:38.500 回答
1
<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() &lt; last()">&amp;</xsl:if>
  </xsl:template> 

</xsl:stylesheet>

outputs

P1=123&P2=456&P3=789

Note that you actually should use URL encoding on the values of each <text>, but that's not built into XSLT 1.0 (but 2.0 has a function for it).

If you are dealing with number values you should be fine, if not you should look for ways to get a URL encoding function into your stylesheet. There are several ways to extend XSLT with external functions, it depends on your XSLT engine which one applies to you.

于 2013-10-16T16:26:10.040 回答
1

有时它更容易使用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">&amp;</xsl:if>T<xsl:value-of select="position()" />=<xsl:value-of select="." />
        </xsl:for-each> 
    </xsl:template>
</xsl:stylesheet>
于 2013-10-16T16:21:51.823 回答
0

它可以像这样在 XPath 2.0(以及 XSLT 2.0)中完成:

string-join(
  for $i in 1 to count(//text) 
    return concat('T', $i, '=', (//text)[$i]), 
  '&')
于 2013-10-16T21:59:20.427 回答