1

Possible Duplicate:
Xpath fails if an element has a a xmlns attribute

I have been trying for a long time to extract a string from the following xml with no luck http://chris.photobooks.com/xml/default.htm?state=8T

I am trying to get the ASIN number of a book and I have tried

$xpath->query('//MarketplaceASIN/ASIN')->item(0)->nodeValue;

and

$xpath->query('/GetMatchingProductResponse/GetMatchingProductResult[1]/Product/Identifiers/MarketplaceASIN/ASIN')->item(0)->nodeValue;

but neither seem to work, what am I doing wrong here?

Community
  • 1
  • 1
mk_89
  • 2,692
  • 7
  • 44
  • 62

1 Answers1

1

The elements in that document are bound to the namespace http://mws.amazonservices.com/schema/Products/2011-10-01.

You may have missed it because it does not use a namespace-prefix and the xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" just looks like an attribute, but namespace attributes are special.

All of the descendant elements inherit that namespace. You will want to register the namespace with a namespace-prefix and adjust your XPath:

$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI); 
$xpath->registerNamespace('a', $rootNamespace); 
$elementList = $xpath->query('//a:MarketplaceASIN/a:ASIN');

Or you could use a more generic XPath that matches on elements and uses a predicate filter to match the local-name() and namespace-uri():

//*[local-name()='MarketplaceASIN' and namespace-uri()='http://mws.amazonservices.com/schema/Products/2011-10-01']/*[local-name()='ASIN' and namespace-uri()='http://mws.amazonservices.com/schema/Products/2011-10-01']
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147