【发布时间】:2020-10-13 09:16:17
【问题描述】:
我是 XSLT 的新手,虽然将 XML 转换为 HTML 是相当可行的,但我正在努力将 XML 转换为 XML。我想做的事情应该很简单,但我无可救药地卡住了。考虑这个 XML 文件:
<cookbook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://jg.dhlab.de/Teaching/recipe.xsd">
<recipe name="Apple pie">
<ingredients name='Apples'/>
<ingredients name='Butter'/>
<ingredients name="Flour"/>
<ingredients name="Cinnamon"/>
<ingredients name="Sugar"/>
<ingredients name="Eggs"/>
<instructions>In a small bowl, combine the sugars, flour and spices; set aside. In a large bowl, toss apples with lemon juice. Add sugar mixture; toss to coat. Line a 9-in. pie plate with bottom crust; trim even with edge. Fill with apple mixture; dot with butter. Roll remaining crust to fit top of pie; place over filling. Trim, seal and flute edges. Cut slits in crust.
Beat egg white until foamy; brush over crust. Sprinkle with sugar. Cover edges loosely with foil. Bake at 375° for 25 minutes. Remove foil and bake until crust is golden brown and filling is bubbly, 20-25 minutes longer. Cool on a wire rack.</instructions>
</recipe>
</cookbook>
我想将成分元素的名称属性转换为子元素(即同时保留成分元素。我使用的 XSL:
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="ingredients">
<xsl:element name="{name(@name)}">
<xsl:value-of select="@name"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
但是,此 XSL 将 name 属性转换为元素,但覆盖了成分元素。我想要的是以下输出:
<recipe name="Apple pie">
<ingredients>
<name>Apples</name>
<name>Butter</name>
<name>Flour</name>
<name>Cinnamon</name>
<name>Sugar</name>
<name>Eggs</name>
</ingredients>
<instructions>In a small bowl, combine the sugars, flour and spices; set aside. In a large bowl, toss apples with lemon juice. Add sugar mixture; toss to coat. Line a 9-in. pie plate with bottom crust; trim even with edge. Fill with apple mixture; dot with butter. Roll remaining crust to fit top of pie; place over filling. Trim, seal and flute edges. Cut slits in crust.
Beat egg white until foamy; brush over crust. Sprinkle with sugar. Cover edges loosely with foil. Bake at 375° for 25 minutes. Remove foil and bake until crust is golden brown and filling is bubbly, 20-25 minutes longer. Cool on a wire rack.</instructions>
</recipe>
谁能告诉我如何实现这一目标以及我做错了什么?
【问题讨论】: