SigGP
SigGP

Reputation: 786

Creating tag QNames from element text

I have two questions connected with transformation XML to XML.

  1. How make a new element which name is value of existing element (in my example the value of existing element <author> is Mike and I want to make a new tag named Mike).

  2. How make a new element which attribute name is value of existing element (in my example the value of existing element <grade> is 5 and I want to make a new tag named Mike with attribute name "5"). Here is my example:

Existing XML:

<art>
  <images>
    <image>
      <title>Cat</title>
      <author>Mike</author>
      <grade>5<grade>
    </image>
    <image>
      <title>Snake</title>
      <author>John</author>
      <grade>4<grade>
    </image>
  </images>
</art>

New element inside tag art:

<authors>
  <Mike grade="5">
    <field_of_art>photography</field_of_art>
  </Mike>
</authors>

Upvotes: 0

Views: 24

Answers (1)

Dan Field
Dan Field

Reputation: 21661

So you can do this using <xsl:element> and <xsl:attribute> tags:

<!-- assumes the current context is an image tag -->
<xsl:element name="{author}">
    <xsl:attribute name="grade">
        <xsl:value-of select="grade" />
    </xsl:attribute>
    <field_of_art>photography</field_of_art>
</xsl:element>

But be aware - if the author tag contains spaces or invalid characters it won't work. For example, if you have an <author>Mike 2</author>, the stylesheet will fail because tag names can't have spaces, or if there were an <author>Mike&amp;Jane</author> it would fail as well.

Upvotes: 2

Related Questions