Convert attribute value into element

2020-02-06 09:53发布

I'm trying to transform this xml:

<tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>

into this xml:

<tokens>
 <a>
  <b>nomX</b>
  <c>prenomX</c>
  <d>villeX</d>
 </a>
 <a>
  <b>nomY</b>
  <c>prenomY</c>
  <d>villeY</d>
 </a>
 <e>nomZ</e>
</tokens>

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet. If anyone has an idea, it would be greatly appreciated.

Thx.

标签: xml xslt
3条回答
男人必须洒脱
2楼-- · 2020-02-06 10:17

I used your answer to find the right xsl:

here is what i use:

<xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

Thank a lot !

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-06 10:39

This should do the trick:

<xsl:template match="token">
  <xsl:element name="{@cle}">
    <xsl:apply-templates select="*|@*"/>
  </xsl:element>
</xsl:template>

for more info on xsl:element see: http://www.w3.org/TR/xslt#section-Creating-Elements-with-xsl:element

you might want to add some xsl:if to check if there really is a @cle attribute, but otherwise this should work fine

查看更多
Summer. ? 凉城
4楼-- · 2020-02-06 10:40

so xslt is the right way I think:

<?xml version="1.0" encoding="UTF-8"?>
<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="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>
查看更多
登录 后发表回答