diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 6e63d8ea25..790d86a75a 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -27,6 +27,11 @@ class Crawler extends \SplObjectStorage */ protected $uri; + /** + * @var string The default namespace prefix to be used with XPath and CSS expressions + */ + private $defaultNamespacePrefix = 'default'; + /** * Constructor. * @@ -708,6 +713,16 @@ class Crawler extends \SplObjectStorage return $form; } + /** + * Overloads a default namespace prefix to be used with XPath and CSS expressions. + * + * @param string $prefix + */ + public function setDefaultNamespacePrefix($prefix) + { + $this->defaultNamespacePrefix = $prefix; + } + /** * Converts string for XPath expressions. * @@ -806,7 +821,7 @@ class Crawler extends \SplObjectStorage foreach ($prefixes as $prefix) { // ask for one namespace, otherwise we'd get a collection with an item for each node - $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', 'default' === $prefix ? '' : $prefix)); + $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix)); if ($node = $namespaces->item(0)) { $domxpath->registerNamespace($prefix, $node->nodeValue); } else { @@ -824,7 +839,7 @@ class Crawler extends \SplObjectStorage */ private function findNamespacePrefixes($xpath) { - if (preg_match_all('/(?P[a-zA-Z_][a-zA-Z_0-9\-\.]+):[^:]/', $xpath, $matches)) { + if (preg_match_all('/(?P[a-zA-Z_][a-zA-Z_0-9\-\.]*):[^:]/', $xpath, $matches)) { return array_unique($matches['prefix']); } diff --git a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php index cca6165fc2..54760b7bed 100644 --- a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php @@ -378,6 +378,16 @@ EOF $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text()); } + public function testFilterXPathWithCustomDefaultNamespace() + { + $crawler = $this->createTestXmlCrawler(); + $crawler->setDefaultNamespacePrefix('x'); + $crawler = $crawler->filterXPath('//x:entry/x:id'); + + $this->assertCount(1, $crawler, '->filterXPath() automatically registers a namespace'); + $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text()); + } + public function testFilterXPathWithNamespace() { $crawler = $this->createTestXmlCrawler()->filterXPath('//yt:accessControl');