Eugene Yao
Eugene Yao

Reputation: 15

How to template match the first child node of the root node xslt

I've been googling for an hour and none of the answers I've found have solved this problem.

Here is a snippet of my xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
        <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>foobar</groupId>
        <artifactId>superpom</artifactId>
        <version>0.1.0.5</version>
    </parent>

        <artifactId>common-parent</artifactId>
        <version>0.2.0.4-SNAPSHOT</version>
    <packaging>pom</packaging>


    <properties>
        <protostuff.version>1.0.7</protostuff.version>
        <version>2.0.12.0</version>
    </properties>

What I would like is to replace the very first 'version' node's value to be changed to something else.

<?xml version="1.0" encoding="UTF-8"?>
<project>
        <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>foobar</groupId>
        <artifactId>superpom</artifactId>
        <version>0.1.0.5</version>
    </parent>

        <artifactId>common-parent</artifactId>
        <version>THIS HAS CHANGED</version>
    <packaging>pom</packaging>


    <properties>
        <protostuff.version>1.0.7</protostuff.version>
        <version>2.0.12.0</version>
    </properties>

So far this is my xslt file

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:param name="pReplacement" select="'THIS HAS CHANGED'"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="//version[2]">
        <xsl:value-of select="$pReplacement"/>
    </xsl:template>
</xsl:stylesheet>

I've been playing with the value in "match" and nothing has worked. I've tried "version", "/version", "version[2]". Nothing has worked. I don't know if this matters, but I'm using xsltproc on a red hat server to run the transformation. Can anyone please help?

Upvotes: 0

Views: 751

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167571

Use

<xsl:template match="/project/version[1]">
  <xsl:copy>
    <xsl:value-of select="pReplacement"/>
  </xsl:copy>
</xsl:template>

Upvotes: 1

Related Questions