使用命名空间解析XML响应

时间:2014-09-15 05:36:20

标签: php xml xpath namespaces nodes

我正在向亚马逊发送获取产品信息的请求,我收到了来自XML格式的回复 - 看起来像这样:

<?xml version="1.0"?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <GetMatchingProductForIdResult Id="3U-R7EP-QODZ" IdType="SellerSKU" status="Success">
    <Products>
      <Product>
        <Identifiers>
          <MarketplaceASIN>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>B0002DV7Z2</ASIN>
          </MarketplaceASIN>
        </Identifiers>
        <AttributeSets>
          <ns2:ItemAttributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
            <ns2:Binding>Electronics</ns2:Binding>
            <ns2:Brand>Pioneer</ns2:Brand>
            <ns2:Color>Black</ns2:Color>
            <ns2:Feature>Whether a DJ, studio musician, sound engineer or just an avid music listener, the HDJ-1000 is the answer to all of your headphone needs.</ns2:Feature>
            <ns2:Feature>Large diameter speaker units.</ns2:Feature>
            <ns2:Feature>Folding housing with universal joints.</ns2:Feature>
            <ns2:Feature>Stereo/Mono selector switch allows mix of left and right channel signals for single ear monitoring.</ns2:Feature>
            <ns2:Feature>Removable 1/4" jack reveals mini plug for flexible connections, includes carrying case.</ns2:Feature>
            <ns2:ItemDimensions>
              <ns2:Height Units="inches">11.50</ns2:Height>
              <ns2:Length Units="inches">13.00</ns2:Length>
              <ns2:Width Units="inches">12.60</ns2:Width>
              <ns2:Weight Units="pounds">0.60</ns2:Weight>
            </ns2:ItemDimensions>
            <ns2:IsAutographed>false</ns2:IsAutographed>
            <ns2:IsMemorabilia>false</ns2:IsMemorabilia>
            <ns2:Label>Pioneer Pro DJ</ns2:Label>
            <ns2:ListPrice>
              <ns2:Amount>200.00</ns2:Amount>
              <ns2:CurrencyCode>USD</ns2:CurrencyCode>
            </ns2:ListPrice>
            <ns2:Manufacturer>Pioneer Pro DJ</ns2:Manufacturer>
            <ns2:Model>HDJ-1000</ns2:Model>
            <ns2:NumberOfItems>1</ns2:NumberOfItems>
            <ns2:PackageDimensions>
              <ns2:Height Units="inches">4.20</ns2:Height>
              <ns2:Length Units="inches">10.00</ns2:Length>
              <ns2:Width Units="inches">9.50</ns2:Width>
              <ns2:Weight Units="pounds">1.30</ns2:Weight>
            </ns2:PackageDimensions>
            <ns2:PackageQuantity>1</ns2:PackageQuantity>
            <ns2:PartNumber>HDJ-1000</ns2:PartNumber>
            <ns2:ProductGroup>Musical Instruments</ns2:ProductGroup>
            <ns2:ProductTypeName>SOUND_AND_RECORDING_EQUIPMENT</ns2:ProductTypeName>
            <ns2:ProductTypeSubcategory>26705100</ns2:ProductTypeSubcategory>
            <ns2:Publisher>Pioneer Pro DJ</ns2:Publisher>
            <ns2:ReleaseDate>2008-12-08</ns2:ReleaseDate>
            <ns2:SmallImage>
              <ns2:URL>http://ecx.images-amazon.com/images/I/31I5ac8P-wL._SL75_.jpg</ns2:URL>
              <ns2:Height Units="pixels">75</ns2:Height>
              <ns2:Width Units="pixels">75</ns2:Width>
            </ns2:SmallImage>
            <ns2:Studio>Pioneer Pro DJ</ns2:Studio>
            <ns2:Title>Pioneer HDJ-1000 DJ Headphones</ns2:Title>
            <ns2:Warranty>1 Year Exchange</ns2:Warranty>
          </ns2:ItemAttributes>
        </AttributeSets>
        <Relationships>
          <VariationParent xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
            <Identifiers>
              <MarketplaceASIN>
                <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
                <ASIN>B0074L8U64</ASIN>
              </MarketplaceASIN>
            </Identifiers>
          </VariationParent>
        </Relationships>
        <SalesRankings>
          <SalesRank>
            <ProductCategoryId>musical_instruments_display_on_website</ProductCategoryId>
            <Rank>28094</Rank>
          </SalesRank>
        </SalesRankings>
      </Product>
    </Products>
  </GetMatchingProductForIdResult>
  <GetMatchingProductForIdResult Id="86-CK3P-PHK6" IdType="SellerSKU" status="Success">
    <Products>
      <Product>
        <Identifiers>
          <MarketplaceASIN>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>0061785679</ASIN>
          </MarketplaceASIN>
        </Identifiers>
        <AttributeSets>
          <ns2:ItemAttributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
            <ns2:Author>Rollins, James</ns2:Author>
            <ns2:Binding>Mass Market Paperback</ns2:Binding>
            <ns2:Brand>Harper</ns2:Brand>
            <ns2:Edition>Reprint</ns2:Edition>
            <ns2:Feature>Great product!</ns2:Feature>
            <ns2:ItemDimensions>
              <ns2:Height Units="inches">1.90</ns2:Height>
              <ns2:Length Units="inches">7.20</ns2:Length>
              <ns2:Width Units="inches">4.20</ns2:Width>
              <ns2:Weight Units="pounds">0.70</ns2:Weight>
            </ns2:ItemDimensions>
            <ns2:Label>Harper</ns2:Label>
            <ns2:Languages>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Unknown</ns2:Type>
              </ns2:Language>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Original Language</ns2:Type>
              </ns2:Language>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Published</ns2:Type>
              </ns2:Language>
            </ns2:Languages>
            <ns2:ListPrice>
              <ns2:Amount>9.99</ns2:Amount>
              <ns2:CurrencyCode>USD</ns2:CurrencyCode>
            </ns2:ListPrice>
            <ns2:Manufacturer>Harper</ns2:Manufacturer>
            <ns2:NumberOfItems>1</ns2:NumberOfItems>
            <ns2:NumberOfPages>576</ns2:NumberOfPages>
            <ns2:PackageDimensions>
              <ns2:Height Units="inches">1.70</ns2:Height>
              <ns2:Length Units="inches">7.40</ns2:Length>
              <ns2:Width Units="inches">4.10</ns2:Width>
              <ns2:Weight Units="pounds">0.70</ns2:Weight>
            </ns2:PackageDimensions>
            <ns2:ProductGroup>Book</ns2:ProductGroup>
            <ns2:ProductTypeName>ABIS_BOOK</ns2:ProductTypeName>
            <ns2:PublicationDate>2014-01-28</ns2:PublicationDate>
            <ns2:Publisher>Harper</ns2:Publisher>
            <ns2:ReleaseDate>2014-01-28</ns2:ReleaseDate>
            <ns2:SmallImage>
              <ns2:URL>http://ecx.images-amazon.com/images/I/51evv9CZCOL._SL75_.jpg</ns2:URL>
              <ns2:Height Units="pixels">75</ns2:Height>
              <ns2:Width Units="pixels">42</ns2:Width>
            </ns2:SmallImage>
            <ns2:Studio>Harper</ns2:Studio>
            <ns2:Title>The Eye of God (Sigma Force)</ns2:Title>
          </ns2:ItemAttributes>
        </AttributeSets>
        <Relationships/>
        <SalesRankings>
          <SalesRank>
            <ProductCategoryId>book_display_on_website</ProductCategoryId>
            <Rank>10083</Rank>
          </SalesRank>
        </SalesRankings>
      </Product>
    </Products>
  </GetMatchingProductForIdResult>
  <GetMatchingProductForIdResult Id="NX-USS1-UXRY" IdType="SellerSKU" status="Success">
    <Products>
      <Product>
        <Identifiers>
          <MarketplaceASIN>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>0375705244</ASIN>
          </MarketplaceASIN>
        </Identifiers>
        <AttributeSets>
          <ns2:ItemAttributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
            <ns2:Author>Ellis, Joseph J.</ns2:Author>
            <ns2:Binding>Paperback</ns2:Binding>
            <ns2:Brand>Vintage</ns2:Brand>
            <ns2:Feature>Great product!</ns2:Feature>
            <ns2:ItemDimensions>
              <ns2:Height Units="inches">0.65</ns2:Height>
              <ns2:Length Units="inches">7.84</ns2:Length>
              <ns2:Width Units="inches">5.48</ns2:Width>
              <ns2:Weight Units="pounds">0.51</ns2:Weight>
            </ns2:ItemDimensions>
            <ns2:Label>Vintage</ns2:Label>
            <ns2:Languages>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Unknown</ns2:Type>
              </ns2:Language>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Original Language</ns2:Type>
              </ns2:Language>
              <ns2:Language>
                <ns2:Name>english</ns2:Name>
                <ns2:Type>Published</ns2:Type>
              </ns2:Language>
            </ns2:Languages>
            <ns2:ListPrice>
              <ns2:Amount>15.95</ns2:Amount>
              <ns2:CurrencyCode>USD</ns2:CurrencyCode>
            </ns2:ListPrice>
            <ns2:Manufacturer>Vintage</ns2:Manufacturer>
            <ns2:NumberOfItems>1</ns2:NumberOfItems>
            <ns2:NumberOfPages>304</ns2:NumberOfPages>
            <ns2:PackageDimensions>
              <ns2:Height Units="inches">1.10</ns2:Height>
              <ns2:Length Units="inches">7.70</ns2:Length>
              <ns2:Width Units="inches">5.10</ns2:Width>
              <ns2:Weight Units="pounds">0.50</ns2:Weight>
            </ns2:PackageDimensions>
            <ns2:PackageQuantity>1</ns2:PackageQuantity>
            <ns2:PartNumber>9780375705243</ns2:PartNumber>
            <ns2:ProductGroup>Book</ns2:ProductGroup>
            <ns2:ProductTypeName>ABIS_BOOK</ns2:ProductTypeName>
            <ns2:PublicationDate>2002-02-05</ns2:PublicationDate>
            <ns2:Publisher>Vintage</ns2:Publisher>
            <ns2:ReleaseDate>2002-02-05</ns2:ReleaseDate>
            <ns2:SmallImage>
              <ns2:URL>http://ecx.images-amazon.com/images/I/51KJtm7pCrL._SL75_.jpg</ns2:URL>
              <ns2:Height Units="pixels">75</ns2:Height>
              <ns2:Width Units="pixels">49</ns2:Width>
            </ns2:SmallImage>
            <ns2:Studio>Vintage</ns2:Studio>
            <ns2:Title>Founding Brothers: The Revolutionary Generation</ns2:Title>
          </ns2:ItemAttributes>
        </AttributeSets>
        <Relationships/>
        <SalesRankings>
          <SalesRank>
            <ProductCategoryId>book_display_on_website</ProductCategoryId>
            <Rank>3269</Rank>
          </SalesRank>
          <SalesRank>
            <ProductCategoryId>9681303011</ProductCategoryId>
            <Rank>4</Rank>
          </SalesRank>
          <SalesRank>
            <ProductCategoryId>4871</ProductCategoryId>
            <Rank>7</Rank>
          </SalesRank>
          <SalesRank>
            <ProductCategoryId>11086</ProductCategoryId>
            <Rank>16</Rank>
          </SalesRank>
        </SalesRankings>
      </Product>
    </Products>
  </GetMatchingProductForIdResult>
  <GetMatchingProductForIdResult Id="VB-GNYY-PMZS" IdType="SellerSKU" status="Success">
    <Products>
      <Product>
        <Identifiers>
          <MarketplaceASIN>
            <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
            <ASIN>B00DQAPJSY</ASIN>
          </MarketplaceASIN>
        </Identifiers>
        <AttributeSets>
          <ns2:ItemAttributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-US">
            <ns2:Binding>Personal Computers</ns2:Binding>
            <ns2:Brand>JBL</ns2:Brand>
            <ns2:Color>Red</ns2:Color>
            <ns2:Feature>Versatile, portable design</ns2:Feature>
            <ns2:Feature>Five-hour, Li-ion rechargeable battery</ns2:Feature>
            <ns2:Feature>Built-in microphone &amp; call answer button for mobile devices</ns2:Feature>
            <ns2:Label>JBL</ns2:Label>
            <ns2:ListPrice>
              <ns2:Amount>119.95</ns2:Amount>
              <ns2:CurrencyCode>USD</ns2:CurrencyCode>
            </ns2:ListPrice>
            <ns2:Manufacturer>JBL</ns2:Manufacturer>
            <ns2:MediaType>MP3</ns2:MediaType>
            <ns2:Model>JBLFLIPREDAM</ns2:Model>
            <ns2:PackageDimensions>
              <ns2:Height Units="inches">2.90</ns2:Height>
              <ns2:Length Units="inches">7.50</ns2:Length>
              <ns2:Width Units="inches">7.10</ns2:Width>
              <ns2:Weight Units="pounds">1.70</ns2:Weight>
            </ns2:PackageDimensions>
            <ns2:PackageQuantity>1</ns2:PackageQuantity>
            <ns2:PartNumber>JBLFLIPREDAM</ns2:PartNumber>
            <ns2:ProductGroup>Network Media Player</ns2:ProductGroup>
            <ns2:ProductTypeName>PORTABLE_AUDIO</ns2:ProductTypeName>
            <ns2:Publisher>JBL</ns2:Publisher>
            <ns2:SmallImage>
              <ns2:URL>http://ecx.images-amazon.com/images/I/410I6YxfTtL._SL75_.jpg</ns2:URL>
              <ns2:Height Units="pixels">65</ns2:Height>
              <ns2:Width Units="pixels">75</ns2:Width>
            </ns2:SmallImage>
            <ns2:Studio>JBL</ns2:Studio>
            <ns2:Title>JBL Flip Wireless Bluetooth Speaker (Red)</ns2:Title>
          </ns2:ItemAttributes>
        </AttributeSets>
        <Relationships/>
        <SalesRankings>
          <SalesRank>
            <ProductCategoryId>wireless_display_on_website</ProductCategoryId>
            <Rank>17155</Rank>
          </SalesRank>
        </SalesRankings>
      </Product>
    </Products>
  </GetMatchingProductForIdResult>
  <ResponseMetadata>
    <RequestId>c09070bd-cc9b-485b-9df0-e7ff24b014b5</RequestId>
  </ResponseMetadata>
</GetMatchingProductForIdResponse>
ResponseHeaderMetadata: RequestId: c09070bd-cc9b-485b-9df0-e7ff24b014b5, ResponseContext: kTgQHamo26t53ZIXhXJTA7jfRyqcib2iqO1Wf/3khcqgfhHFseHa9JYrX8Dlzs9OrGixmPIsCxuZ jSUoBV3RLw==,YR44XTRP1f51djG65oaAWhdNHw0+6V32WmJmZoqkSTeUVHYvq88nOBfaE6EgXq3XTR9WAss6d97r gR/TimYXbQ==, Timestamp: 2014-09-15T05:23:50.364Z, Quota Max: 17772.0, Quota Remaining: 17772.0, Quota Resets At: 2014-09-15T05:25:00.000Z

我试图获取响应中每个项目(Product)的权重,如果从节点的根元素开始,可以在GetMatchingProductForIdResult/Products/Product/AttributeSets/ns2:ItemAttributes/ns2:ItemDimensions/ns2:Weight找到。我试图像这样使用xpath

$dozy=new DOMDocument();
$dozy->loadXML($response->toXML());

$dozy->preserveWhiteSpace = false;
$dozy->formatOutput = true;

$xpathy = new DOMXpath($dozy);

$xpathy->registerNamespace('ns2', 'http://www.w3.org/XML/2008/xsdl-exx/ns2');

$weighter = $xpathy->query('//GetMatchingProductForIdResult/Products/Product/AttributeSets/ns2:ItemAttributes/ns2:ItemDimensions/ns2:Weight');

然而,当我去参考我所得到的东西时:

echo $weighter->item(0)->nodeValue;

我收到错误说:

Trying to get property of non-object.

我认为这种情况正在发生,因为$weighter为空(它没有存储任何内容),因此item函数无法正常工作。

非常感谢有关如何定位ns2:Weight节点的任何帮助。感谢。

3 个答案:

答案 0 :(得分:1)

出了什么问题

您的原始xpath查询失败有几个原因:

1。)您注册的名称空间&#34; ns2&#34;是不正确的。重要的部分是名称空间URI - 您可以选择任何您喜欢的前缀。所以:

$xpathy->registerNamespace(
    'ns2',
    "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"
);

2.)其他元素有一个默认命名空间,需要在DOMXPath对象中使用前缀和表达式中使用的前缀进行注册。

$xpathy->registerNamespace(
    'ns',
    "http://mws.amazonservices.com/schema/Products/2011-10-01"
);

$weighter = $xpathy->query(
'//ns:GetMatchingProductForIdResult/ns:Products/ns:Product/ns:AttributeSets
/ns2:ItemAttributes/ns2:ItemDimensions/ns2:Weight'
);

可能正确

由于您的回答here表明//*[local-name()="Weight"]'可以正常选择您要查找的内容,因此您实际上可以完全跳过所有xpath内容并使用:

$weighter = $dozy->getElementsByTagName('Weight');

但是,您可以找到getElementsByTagName()和缩写的xpath,但最终会得到的元素数量超过原始xpath的更正版本。

这是因为原作只是在//ns2:ItemDimensions/ns2:Weight处寻找那些新的缩短方式也会在//ns2:PackageDimensions/ns2:Weight找到的人。


可能是正确的 er

要完全放置内容以获得结果,原始内容会检索到您的内容,例如:

$dozy=new DOMDocument();
$dozy->loadXML($response->toXML());

$dozy->preserveWhiteSpace = false;
$dozy->formatOutput = true;

$xpathy = new DOMXpath($dozy);

$xpathy->registerNamespace(
    'ns2',
    "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"
);
$xpathy->registerNamespace(
    'ns',
    "http://mws.amazonservices.com/schema/Products/2011-10-01"
);

$weighter = $xpathy->query(
    '//ns:GetMatchingProductForIdResult/ns:Products/ns:Product/ns:AttributeSets
    /ns2:ItemAttributes/ns2:ItemDimensions/ns2:Weight'
);

foreach ($weighter as $node) {
    echo $node->nodeValue, "\n";
}

或者:

(稍短,但仍然与给定的样本数据一样具体。)

$dozy=new DOMDocument();
$dozy->loadXML($response->toXML());

$dozy->preserveWhiteSpace = false;
$dozy->formatOutput = true;

$xpathy = new DOMXpath($dozy);

$xpathy->registerNamespace(
    'ns2',
    "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"
);

$weighter = $xpathy->query(
    '//ns2:ItemDimensions/ns2:Weight'
);

foreach ($weighter as $node) {
    echo $node->nodeValue, "\n";
}

其中任何一个都将输出:

0.60
0.70
0.51

答案 1 :(得分:0)

这有效:

$weighter = $xpathy->query('//*[local-name()="Weight"]');

答案 2 :(得分:0)

XML中的

ns2名称空间前缀声明如下:

<ns2:ItemAttributes 
     xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" 
     xml:lang="en-US">

您需要注册相应的名称空间URI:

$xpathy->registerNamespace('ns2', 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd');