Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT Replace tag value by default

Tags:

xml

xslt

xpath

I have this XML document :

<Document>
    <a>
        <b>
            <c1>CCC111</c1>
            <c2>CCCC222</c2>
        </b>
        <d>
            <d1>DDD111</d1>
            <d2>DDD222</d2>
            <d3>DDD333</d3>
        </d>
</a>
</Document>

I want to replace the value of Document/a/d/d1 by XXXXXX :

<Document>
    <a>
        <b>
            <c1>CCC111</c1>
            <c2>CCCC222</c2>
        </b>
        <d>
            <d1>XXXXXX</d1>
            <d2>DDD222</d2>
            <d3>DDD333</d3>
        </d>
</a>
</Document>

I have this XSLT :

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="Document/a/d/d1/text()">
       XXXXXX
 </xsl:template>

</xsl:stylesheet>

But I obtain the same input and output :/

Thank you.

like image 955
L. Quastana Avatar asked Aug 05 '26 10:08

L. Quastana


1 Answers

in my input file i have : <Document xmlns="tatatta" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="totoot">

This means that the elements in your document are in the tatatta namespace, and since unprefixed names in XPath 1.0 always refer to non-namespaced elements your template won't match. You need to map the namespace to a prefix and use that in the pattern, e.g.:

<xsl:template match="t:Document/t:a/t:d/t:d1/text()"
              xmlns:t="tatatta">
  <xsl:text>XXXXXX</xsl:text>
</xsl:template>

(or you could put the xmlns:t on your xsl:stylesheet instead of on the template, if you need to use the same namespace in other places).

like image 135
Ian Roberts Avatar answered Aug 07 '26 03:08

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!