adding attributes to xml output

Here should go questions about transforming XML with XSLT and FOP.
jojo33
Posts: 1
Joined: Wed Jan 09, 2008 3:38 am

adding attributes to xml output

Post by jojo33 »

Hello,

I want to add attributes to all elements called <outil> that are children of the rootelement <Listeoutils>. I want to copy all elements and attributes of the source xml document via the xslt stylesheet into an output xml document. then I want to add to all <outil> elements that have an attribute called "bibliothèque" a new attribute with the name "id_type" that has the value "1". I wrote this code but it doesn't work: Where is the mistake?

<?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" encoding="utf-8"/>

<xsl:preserve-space elements="*"/>

<xsl:template match="/">
<xsl:copy>
<xsl:copy-of select="/"/>
<xsl:apply-templates select="//outil"/>
</xsl:copy>
</xsl:template>


<xsl:template match="outil">
<xsl:for-each select="outil">
<xsl:choose>

<xsl:when test="@type='bibliothèque'">
<outil>
<xsl:attribute name="id_type">1</xsl:attribute>
</outil>
</xsl:when>


<xsl:otherwise>
<outil>
<xsl:attribute name="id_type">100</xsl:attribute>
</outil>
</xsl:otherwise>


</xsl:choose>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:template>


</xsl:stylesheet>
Dan
Posts: 501
Joined: Mon Feb 03, 2003 10:56 am

Post by Dan »

Hello,
I understand that you have some XML of the form:

Code: Select all


<test>
<listeoutils>
<outil type='bibliothèque' at1="x" at2="y">
<outil-content/>
</outil>
<outil type='other' at2="z" at3="t">
<outil-content2/>
</outil>
</listeoutils>
</test>
Here is a stylesheet that copies the input and adds the required attributes:

Code: Select all


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:preserve-space elements="*"/>

<!-- Match document -->
<xsl:template match="/">
<xsl:apply-templates mode="copy" select="."/>
</xsl:template>

<!-- Deep copy template -->
<xsl:template match="*|text()|@*" mode="copy">
<xsl:copy>
<xsl:apply-templates mode="copy" select="@*"/>
<xsl:apply-templates mode="copy"/>
</xsl:copy>
</xsl:template>
<!-- Handle default matching -->
<xsl:template match="*"/>

<xsl:template match="outil" mode="copy">
<outil>
<!-- Copy the attributes -->
<xsl:apply-templates mode="copy" select="@*"/>

<xsl:choose>
<xsl:when test="@type='bibliothèque'">
<xsl:attribute name="id_type">1</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name="id_type">100</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
<!-- Content -->
<xsl:apply-templates mode="copy"/>
</outil>
</xsl:template>
</xsl:stylesheet>
Another way of copying attributes is to use directly:

Code: Select all

 
<xsl:for-each select="@*">
<xsl:attribute name="{name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:for-each>
I hope this helps.
Post Reply