【问题标题】:parse XML response with namespaces使用命名空间解析 XML 响应
【发布时间】:2014-09-15 05:36:19
【问题描述】:

我正在向亚马逊发送一个获取产品信息的请求,并且我收到了他们的 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

我正在尝试获取响应中每个项目(产品)的权重,如果您从节点的根元素开始,可以在 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-&gt;item(0)-&gt;nodeValue;

我收到一条错误消息:

Trying to get property of non-object.

我认为这是因为$weighter 为空(它没有存储任何内容)所以item 函数不起作用。

任何有关如何定位 ns2:Weight 节点的帮助将不胜感激。谢谢。

【问题讨论】:

    标签: php xml xpath namespaces nodes


    【解决方案1】:

    出了什么问题

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

    1.) 您为“ns2”注册的命名空间不正确。重要的部分是名称空间 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 的那些。


    什么是对的

    为了得到原始文件会检索到的结果,您正在查看类似的内容:

    $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
    

    【讨论】:

      【解决方案2】:

      这行得通:

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

      【讨论】:

        【解决方案3】:

        ns2 XML 中的命名空间前缀声明如下:

        <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');
        

        【讨论】:

          猜你喜欢
          • 2012-03-26
          • 2019-04-21
          • 2012-12-05
          • 2021-05-03
          • 2014-01-10
          • 2010-11-08
          • 2018-07-15
          相关资源
          最近更新 更多