Home > Back-end >  How can I select nodes in XSLT when the node is named <foo:bar>?
How can I select nodes in XSLT when the node is named <foo:bar>?

Time:12-06

I have an XML file with a structure like this:

<Products>
 <Product>
  <sku>1234567</sku>
  <attribute:pa_brand xmlns:attribute="attribute">bugatti</attribute:pa_brand>
  <attribute_data:pa_brand xmlns:attribute_data="attribute_data">5|1|0</attribute_data:pa_brand>
 </Product>
</Products>

I'm trying to select all products from a certain brand. I tried the following XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <Products>
      <xsl:apply-templates select="//Product[attribute:pa_brand  = 'bugatti']"/>
    </Products>
  </xsl:template>

  <xsl:template match="Product">
    <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

Using XML Starlet on Mac OS it gives me: Failed to evaluate the 'select' expression.

Adding single quotes to the node name: select="//Product['attribute:pa_brand' = 'bugatti']"/> runs the query, but returns no results.

Using a simple node in the select, i.e.: 'sku' like this: //Product[sku='123456'] works OK. I couldn't even find out what this notation is called <foo:bar></foo:bar>. I don't know how the 'bar' part of the node name is called. Tried W3CSchools and various references. All examples and references, that I found, describe just simple nodes, or nodes with attributes<foo></foo> or <foo bar='baz'></foo>. Couldn't find any <foo:bar>baz</foo:bar> reference.

CodePudding user response:

How about:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:attribute="attribute">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Products">
    <xsl:copy>
        <xsl:copy-of select="Product[attribute:pa_brand = 'bugatti']"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Note the namespace declaration in the xsl:stylesheet element.

  • Related