Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have the following test case:

use strict; use warnings; use Test::More 'no_plan'; use Test::XML::XPath; my $html = <<'END'; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> </body> </html> END like_xpath $html, '/html', 'An XHTML document';

That test fails to match the XHTML. What am I doing wrong and how can I diagnose this in the future? Also, it takes three seconds to fail to match. If I remove the DOCTYPE, it matches instantly. What's happening with that?

Replies are listed 'Best First'.
Re: Test::XML::XPath doesn't match
by Ovid (Cardinal) on Aug 12, 2009 at 10:33 UTC

    As far as I can tell, Test::XML::XPath won't let you do this directly. I'm unsure why, but it seems like you really need to find a way to register the XHTML namespace. You'll hate this, but the following monkey patch should makes your test pass:

    { no warnings 'redefine'; sub Test::XML::XPath::XML::LibXML::new { my ($class,$xml) = @_; my $p = XML::LibXML->new; $p->line_numbers(1); my $document = $p->parse_string($xml) or croak("Could not parse XML: $xml"); my $xpc = XML::LibXML::XPathContext->new( $document->documentE +lement ); $xpc->registerNs( x => "http://www.w3.org/1999/xhtml" ); return bless { xpath => $xpc } => $class; } }

    The caveat is that you have to now use the 'x' prefix with your xpaths.

    Update:: This assume that you're using XML::LibXML (which I assume you are).

    like_xpath $html, '/x:html', 'An XHTML document';
Re: Test::XML::XPath doesn't match
by Anonymous Monk on Aug 11, 2009 at 20:22 UTC

    I forgot to mention that if I remove the DOCTYPE, this test passes, but actual XML from our application fails with HTML entities not getting recognized (this means invalid XML and we still can't match).