Seems like I never stop banging my head with this =/
And believe me I’m not lazy because I’m asking here .:)
What I’m trying to do now is that I want to give my XML file a new root element.
So my output should be something like this.
<motorpark>
<fordon pris="129900"><name>Honda</name><modellTyp1/></fordon>
<fordon pris="119000"><name>Nissan</name><modellTyp2/></fordon>
</motorpark>
But I cant seem to point out my template correct.
ether way It prints out my whole XML file, without even read my XSL file
Or I get on every element thats printing out.
This is what I accomplish for the moment with some help from lwburk here on stackoverflow 🙂
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="ad">
<xsl:element name="motorpark">
<xsl:apply-templates select="autoads" mode="ad"/>
</xsl:element>
</xsl:template>
<xsl:template match="ad">
<xsl:element name="fordon">
<xsl:attribute name="pris">
<xsl:copy-of select="price" />
</xsl:attribute>
<xsl:copy-of select="name"/>
<xsl:element name="{concat('modellTyp', type)}">
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
My XML file is looking like this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="uppgift2.xsl"?>
<autoads>
<ad>
<type>1</type>
<name>Honda</name>
<model>XL 1000 V</model>
<regyear>2001</regyear>
<price>129900</price>
<adtext>2001 Honda XL 1000 V, 8.900 km. hög vindruta. Pris 129.900kr,-. </adtext>
<addate>20020115</addate>
<volume>1000</volume>
<category></category>
</ad>
<ad>
<type>2</type>
<name>Nissan</name>
<model>Almera 1.4S</model>
<regyear>1997</regyear>
<price>119000</price>
<adtext>1997 Nissan Almera 1.4S, 5 dörrar, met, 70.000 km. el.spegel/fönster, galv. kaross, c.lås, startspärr, airbag, nedfällb. baks. ABS, ute temp. R/CD, alarm, d.fäste, v.säten, s/v-hj. EU-godk. full service, servo. Pris 119.000 kr,-. </adtext>
<addate>20020118</addate>
<volume>0</volume>
<category>5 dörrar</category>
</ad>
</autoads>
The following stylesheet produces the desired result:
Notice that the stylesheet’s size can be greatly reduced by hardcoding element and attribute names when they’re known in advance.
xsl:elementandxsl:attributeare usually only necessary when producing dynamic content. Also, note that you previously had two templates matching exactly the same element. We’re now matching the root (/) andadnodes separately.