Hunsu
Hunsu

Reputation: 3391

How to select element by attribute with xslt

I have this xml file:

<writer id_writer="1">
  <name>name</name>
</writer>

<film id_writer="1">
</film>

How to print the writer of each film using xslt

<xsl:for-each select="film">
   <xsl:value-of select="writer[@id_writer='what to put here']/name"></xsl:value-of>
</xsl:for-each>

Upvotes: 0

Views: 3020

Answers (3)

Captain Normal
Captain Normal

Reputation: 471

The direct answer to your 'what to put here' is

current()/@id_writer

However this is not the only thing needed to make it work, as the writer node is not part of the film node's tree. A complete working answer based on your question:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="text" encoding="iso-8859-1" omit-xml-declaration="yes" />

    <xsl:template match="/body">
        <xsl:for-each select="film">
            <xsl:value-of select="/body/writer[@id_writer=current()/@id_writer]/name"/>
        </xsl:for-each>
    </xsl:template>

</xsl:transform>

Complete XML to feed this:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <writer id_writer="1">
        <name>name</name>
    </writer>

    <film id_writer="1">
    </film>
</body>

Working example here: http://xsltransform.net/bFDb2Ck

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122414

The most efficient way to resolve cross references like this in XSLT is generally to use a key. The key definition goes at the top level of your stylesheet, outside any templates, and specifies which nodes you want to retrieve and how to compute the identifying key value for each one

<xsl:key name="writerById" match="writer" use="@id_writer" />

Once the key is defined you can retrieve matching nodes by key value using a function

<xsl:value-of select="key('writerById', @id_writer)/name"/>

Some XSLT processors (notably recent versions of Saxon EE) will automatically optimise //writer[@id_writer = current()/@id_writer] predicates to execute as efficiently as the explicit key-based approach, but this is not something you can necessarily rely on if you are using an older or less sophisticated processor.

Upvotes: 6

Linga Murthy C S
Linga Murthy C S

Reputation: 5432

I think you are trying to relate film and writer by their attributes, so try this:

<xsl:for-each select="film">
    <xsl:value-of select="../writer[@id_writer=current()/@id_writer]/name"/>
</xsl:for-each>

Upvotes: 1

Related Questions