更改重复的元素名称 xslt xml

  • 本文关键字:xslt xml 元素 xml xslt
  • 更新时间 :
  • 英文 :


我一直在尝试重组XML文件,到目前为止已经能够完成大部分更改。 我需要做的是更改现在已复制的元素的名称,如下所示。

输入

<products>
<product>
<name>name</name>
<description>this description</description>
<code>111</code>
<thumbnail> </thumbnail>
<image1></image1>
<image2></image2>
<image3></image3>
<prodoptions>
<prodoption code="123" description="that description"/>
<prodoption code="456" description="other description"/>
</prodoptions>
</product>
</products>

XSLT

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/products">
<xsl:copy>
<xsl:for-each select="product/prodoptions/prodoption">
<product>
<xsl:copy-of select="../../name"/>
<xsl:copy-of select="../../code"/>
<xsl:copy-of select="../../description"/>
<xsl:copy-of select="../../thumbnail"/>
<xsl:copy-of select="../../image1"/>
<xsl:copy-of select="../../image2"/>
<xsl:copy-of select="../../image3"/>
<xsl:for-each select="@*">
<xsl:element name="{name()}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</product>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

输出

<products>
<product>
<name>name</name>
<code>111</code>
<description>this description</description>
<thumbnail></thumbnail>
<image1></image1>
<image2></image2>
<image3></image3>
<code>123</code>
<description>that description</description>
</product>
<product>
<name>name</name>
<code>111</code>
<description>this description</description>
<thumbnail></thumbnail>
<image1></image1>
<image2></image2>
<image3></image3>
<code>456</code>
<description>other description</description>
</product>
</products>

第二个代码和描述(我从 prodoption 的属性中提取的代码和描述(需要重命名。我之前在将属性转换为元素之前重命名了该属性,但是我发现现在当我这样做时,该属性在应用重命名之前会更改为元素。

好吧,你可以简单地改变这个:

<xsl:element name="name()}">

要说:

<xsl:element name="option-{name()}">

获得:

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<name>name</name>
<code>111</code>
<description>this description</description>
<thumbnail/>
<image1/>
<image2/>
<image3/>
<option-code>123</option-code>
<option-description>that description</option-description>
</product>
<product>
<name>name</name>
<code>111</code>
<description>this description</description>
<thumbnail/>
<image1/>
<image2/>
<image3/>
<option-code>456</option-code>
<option-description>other description</option-description>
</product>
</products>

还有许多其他可能的解决方案,具体取决于您想要实现的确切结果。

最新更新