2015-04-26 21 views
1

我一直在查詢包含默認命名空間的xml文件時出現問題,這已經是一場噩夢。只有在xpath中有默認命名空間時才能選擇第一個節點

我已經能夠在聲明命名空間後選擇第一個節點,但是後面的任何內容都會被忽略。

$str = '<?xml version="1.0"?> 
<GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"> 
    <GetLowestOfferListingsForASINResult> 
     <Product> 
     <LowestOfferListings> 
      <LowestOfferListing> 
      <Qualifiers> 
       <ItemCondition>Used</ItemCondition> 
       <ItemSubcondition>Good</ItemSubcondition> 
       <FulfillmentChannel>Merchant</FulfillmentChannel> 
       <ShipsDomestically>Unknown</ShipsDomestically> 
       <ShippingTime> 
       <Max>0-2 days</Max> 
       </ShippingTime> 
       <SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating> 
      </Qualifiers> 
      <NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered> 
      <SellerFeedbackCount>83352</SellerFeedbackCount> 
      <Price> 
       <LandedPrice> 
       <CurrencyCode>GBP</CurrencyCode> 
       <Amount>7.40</Amount> 
       </LandedPrice> 
       <ListingPrice> 
       <CurrencyCode>GBP</CurrencyCode> 
       <Amount>4.60</Amount> 
       </ListingPrice> 
       <Shipping> 
       <CurrencyCode>GBP</CurrencyCode> 
       <Amount>2.80</Amount> 
       </Shipping> 
      </Price> 
      <MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice> 
      </LowestOfferListing> 
     </LowestOfferListings> 
     </Product> 
    </GetLowestOfferListingsForASINResult> 
</GetLowestOfferListingsForASINResponse>'; 

$xml = new SimpleXMLElement($str); 
$xml->registerXPathNamespace('c', 'http://mws.amazonservices.com/schema/Products/2011-10-01'); 
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult"));   //works 
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult/Product")); //not working 
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult//Product")); //not working 

回答

1

的Xpath沒有自動默認命名空間(它總是null-namespace),所以你需要明確地使用「c:」前綴所有元素名稱:

c:GetLowestOfferListingsForASINResult/c:Product 
             ^^ 

c:GetLowestOfferListingsForASINResult//c:Product 
             ^^ 

如果你有興趣在詳細說明爲什麼是這種情況下,本網站上有以下現有Q & A:

+0

謝謝,這幫了很多忙 –

相關問題