XSL: Add attributes to an empty etiquete with xsl:attribute

Viewed 25

this is my first question so I hope I do it correctly..

So I was trying to transform an xml to another xml with different structure using xslt and I need to add a couple of attributes to an emtpy etiquete and I'm not sure how to do it. The resulting xml should be this:

<categoria tema="INFORMATICA" subtema="PROGRAMACIÓN PHP" />

The xsl looks like this:

<categoria/>
                  <xsl:attribute name="tema">
                      <xsl:value-of select="field[8]"/>
                  </xsl:attribute>
                  <xsl:attribute name="subtema">
                      <xsl:value-of select="field[9]"/>
                  </xsl:attribute>

The original xml is this one (I'll only show the first row):

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="recupera3_01.xsl" ?>
<biblioteca2019>
    <row>
        <field name="TITULO">SQL SERVER 2000</field>
        <field name="ISBN">84-415-1136-5</field>
        <field name="PRECIO">32.89</field>
        <field name="FECHA_ALTA">2021-06-04 19:22:15</field>
        <field name="AUTOR">FRANCISCO CHARTE OJEDA</field>
        <field name="EDITORIAL">ANAYA MULTIMEDIA</field>
        <field name="TEMA">INFORMATICA</field>
        <field name="SUBTEMA">SISTEMAS GESTORES DE BASES DE DATOS</field>
    </row>

How can I make it to look like the first one?

Thanks.

1 Answers

There are a couple of ways that you can do it.

First, if you want to use xsl:attribute to create your attributes, put them inside of that element. Don't be concerned about the fact that it is empty. If you don't put any other content child nodes, then it will be serialized as an empty element:

<xsl:template match="row">
    <categoria>
      <xsl:attribute name="tema" select="field[8]"/>
      <xsl:attribute name="subtema" select="field[9]"/>
    </categoria>
</xsl:template> 

If you know the names of the attributes you want to create, you could use attribute value templates and put them inline in the element:

<xsl:template match="row">
    <categoria tema="{field[8]}" subtema="{field[9]}" />
</xsl:template> 
Related