我是一名初学者,仍在学习 XSLT。我有一个简单的 xml 代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<order id="1021">
<items>
<item code="11">
<quantity>2</quantity
<price>50</price>
</item>
<item code="21">
<quantity>1</quantity>
<price>250</price>
</item>
<item code="13">
<quantity>4</quantity>
<price>100</price>
</item>
</items>
<status>3</status>
</order>
我想编写一个 XSLT 脚本,将其转换为一个包含所有项目代码的简单文本数组。例如,上面的xml应该转换为:
[11,21,13]
我编写了以下 XSLT 代码:
<?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"/>
<xsl:strip-space elements="*"/>
<!-- Template to match the root 'order' element -->
<xsl:template match="/order">
<!-- Start bracket for the array -->
<xsl:text>[</xsl:text>
<!-- Iterate over each item -->
<xsl:for-each select="items/item">
<!-- Output the code attribute -->
<xsl:value-of select="@code"/>
<!-- If not the last item, add a comma and space -->
<xsl:if test="position() != last()">
<xsl:text>, </xsl:text>
</xsl:if>
</xsl:for-each>
<!-- End bracket for the array -->
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
我在迭代所有项目时面临问题。我只得到输出中第一项的代码:
[11]
我期待所有项目的代码,例如:
[11,21,13]
如果有人发现我的 XSLT 代码中的错误,请告诉我。我试过向 chatgpt 询问,但没有太大帮助。
您的 XSLT 1.0 运行良好。
为了进行比较,请参阅下面如何在 XSLT 2.0 中更容易实现。
在 XSLT 2.0 中,
<xsl:value-of>
具有分隔符属性。
输入XML
<?xml version="1.0" encoding="UTF-8"?>
<order id="1021">
<items>
<item code="11">
<quantity>2</quantity>
<price>50</price>
</item>
<item code="21">
<quantity>1</quantity>
<price>250</price>
</item>
<item code="13">
<quantity>4</quantity>
<price>100</price>
</item>
</items>
<status>3</status>
</order>
XSLT 1.0
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<!-- Template to match the root 'order' element -->
<xsl:template match="/order">
<!-- Start bracket for the array -->
<xsl:text>[</xsl:text>
<!-- Iterate over each item -->
<xsl:for-each select="items/item">
<!-- Output the code attribute -->
<xsl:value-of select="@code"/>
<!-- If not the last item, add a comma and space -->
<xsl:if test="position() != last()">
<xsl:text>, </xsl:text>
</xsl:if>
</xsl:for-each>
<!-- End bracket for the array -->
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:text>[</xsl:text>
<xsl:value-of select="order/items/item/@code"
separator=", "/>
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
输出
[11, 21, 13]