【问题标题】:Only able to select first node when there is a default namespace in xpath仅当 xpath 中有默认命名空间时才能选择第一个节点
【发布时间】:2015-07-04 19:26:10
【问题描述】:

我在查询包含默认命名空间的 xml 文件时遇到问题,这是一场噩梦。

在声明命名空间后,我已经能够选择第一个节点,但后面的任何内容都会被忽略。

$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

【问题讨论】:

    标签: php xml xpath


    【解决方案1】:

    Xpath 没有自动默认命名空间(它始终是null-namespace),因此您需要在所有元素名称中显式使用“c:”前缀:

    c:GetLowestOfferListingsForASINResult/c:Product
                                          ^^
    
    c:GetLowestOfferListingsForASINResult//c:Product
                                           ^^
    

    如果您对为什么会这样的详细信息感兴趣,本网站上有以下现有问答:

    【讨论】:

    • 谢谢,帮了大忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多