How to change an attribute conditionally, checking its value of marriage?

I want to change some attribute values โ€‹โ€‹only for a specific item. For example, is it possible to change @lang only for books with a price of 29.99 below XML?

<book>
  <title lang="fr">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
+3
source share
2 answers

This is a short and simple conversion (without explicit conditions at all) :

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

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

 <xsl:template match="book[price=29.99]/title/@lang">
  <xsl:attribute name="lang">ChangedLang</xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

when applied to the provided XML (wrapped in a well-formed XML document):

<t>
    <book>
        <title lang="fr">Harry Potter</title>
        <price>29.99</price>
    </book>
    <book>
        <title lang="eng">Learning XML</title>
        <price>39.95</price>
    </book>
</t>

creates the desired, correct result :

<t>
   <book>
      <title lang="ChangedLang">Harry Potter</title>
      <price>29.99</price>
   </book>
   <book>
      <title lang="eng">Learning XML</title>
      <price>39.95</price>
   </book>
</t>

The explanation . Overriding the rule for the desired attribute.

+3
source

Try something like this:

XML source

<books>
    <book>
        <title lang="fr">Harry Potter</title>
        <price>29.99</price>
    </book>
    <book>
        <title lang="eng">Learning XML</title>
        <price>39.95</price>
    </book>
</books>

XSLT Example

<?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" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <books>
            <xsl:for-each select="books/book">
                <xsl:apply-templates select="."/>
            </xsl:for-each>
        </books>
    </xsl:template>
    <xsl:template match="book">
            <book>
                <title>
                    <xsl:if test="price = '29.99'">
                        <xsl:attribute name="lang">eng</xsl:attribute>
                    </xsl:if>
                <xsl:value-of select="title"/></title>
                <price><xsl:value-of select="price"/></price>
            </book>
    </xsl:template>
</xsl:stylesheet>

Alternative pattern

node? , :

<xsl:template match="title">
    <title>
        <xsl:if test="following-sibling::price[1] = '29.99'">
            <xsl:attribute name="lang">eng</xsl:attribute>
        </xsl:if>
        <xsl:value-of select="."/>
    </title>
</xsl:template>
+1

All Articles