Search code examples
xsltxhtmlxml-namespaces

XSLT matching xhtml namespace


Good day,

I'm trying to match the 'head' element in an xhtml file produced from an html file with the HTML tidy markup corrector using this command line:

tidy -asxml -output test_tidy.html --numeric-entities yes .\test.html

test_tidy.html contains the following xmlns namespace:

 <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>

This XSLT template match doesn't work for me:

<xsl:template match="//head">

What am I missing? Ideally I want to use the same stylesheet for processing XHTML files with or without the xmlns namespace declaration, for example to process this file:

 <!DOCTYPE html>
        <html>
               <head>

Any help gratefully received.

Best wishes!


Solution

  • If you want the same template to match the head element in both:

    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
    

    and:

    <html>
         <head>
    

    you must make your template:

    <xsl:template match="x:head|head">
    

    after declaring xmlns:x="http://www.w3.org/1999/xhtml.


    Alternatively, you could do:

    <xsl:template match="*[local-name()='head']">
    

    or (in XSLT 2.0 or higher):

    <xsl:template match="*:head">
    

    but that's generally not good practice as (at least in theory) there could be other head elements in other namespaces that you do not want to match.