Reputation: 4000
What is the XSLT to get a parent node based on the value of the child?
My xml:
<cast>
<character>
<name>Bugs</name>
<id>1</id>
</character>
<character>
<name>Daffy</name>
<id>2</id>
</character>
I have tried this:
<xsl:template match="/cast/character/id">
<xsl:if test="text()=1">
<xsl:apply-templates select="../self" mode='copier'/>
</xsl:if>
</xsl:template>
<xsl:template match="*" mode='copier'>
<xsl:apply-templates />
</xsl:template>
But this outputs the text of every node in the document.
EDIT: I have to output XML here, I'm planning to extend this to XML generation
Upvotes: 1
Views: 1929
Reputation: 243449
Just use:
<xsl:apply-templates select="/*/character[id=1]"/>
or, if the wanted node should just be copied with no further processing:
<xsl:copy-of select="/*/character[id=1]"/>
Upvotes: 1
Reputation: 1248
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/cast/character">
<xsl:if test="id=1">
<xsl:copy-of select="." />
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Not able to add a comment. Hence put it here
Upvotes: 0
Reputation: 3530
I believe you're printing everything because the processor starts matching at the root and the only template you specify is for id
elements, so things get copied by default. Try this:
<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
<output method="text" />
<template match="/">
<apply-templates select="//id" />
</template>
<template match="id">
<if test="text()='1'">
<value-of select=".." />
</if>
</template>
</stylesheet>
Or if you just want the character name, you could replace the select
attribute value in the value-of
element with "../name
".
Upvotes: 1