ElementTree で XPath を使用する 質問する

ElementTree で XPath を使用する 質問する

私の XML ファイルは次のようになります。

<?xml version="1.0"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19">
  <Items>
    <Item>
      <ItemAttributes>
        <ListPrice>
          <Amount>2260</Amount>
        </ListPrice>
      </ItemAttributes>
      <Offers>
        <Offer>
          <OfferListing>
            <Price>
              <Amount>1853</Amount>
            </Price>
          </OfferListing>
        </Offer>
      </Offers>
    </Item>
  </Items>
</ItemSearchResponse>

私がやりたいのは、ListPrice を抽出することだけです。

私が使用しているコードは次のとおりです:

>> from elementtree import ElementTree as ET
>> fp = open("output.xml","r")
>> element = ET.parse(fp).getroot()
>> e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount')
>> for i in e:
>>    print i.text
>>
>> e
>>

まったく出力されませんでした。

>> e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount')

変わりはない。

何が間違っているのでしょうか?

ベストアンサー1

あなたには2つの問題があります。

1)elementルート要素のみが含まれ、ドキュメント全体が再帰的に含まれません。これは ElementTree ではなく Element タイプです。

2) XML 内に名前空間を保持する場合は、検索文字列で名前空間を使用する必要があります。

問題 1 を解決するには:

変更する必要があるもの:

element = ET.parse(fp).getroot()

に:

element = ET.parse(fp)

問題 2 を解決するには:

XML ドキュメントから xmlns を削除すると、次のようになります。

<?xml version="1.0"?>
<ItemSearchResponse>
  <Items>
    <Item>
      <ItemAttributes>
        <ListPrice>
          <Amount>2260</Amount>
        </ListPrice>
      </ItemAttributes>
      <Offers>
        <Offer>
          <OfferListing>
            <Price>
              <Amount>1853</Amount>
            </Price>
          </OfferListing>
        </Offer>
      </Offers>
    </Item>
  </Items>
</ItemSearchResponse>

このドキュメントでは、次の検索文字列を使用できます。

e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount')

完全なコード:

from elementtree import ElementTree as ET
fp = open("output.xml","r")
element = ET.parse(fp)
e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount')
for i in e:
  print i.text

問題 2 の代替修正:

それ以外の場合は、各要素の sresearch 文字列内で xmlns を指定する必要があります。

完全なコード:

from elementtree import ElementTree as ET
fp = open("output.xml","r")
element = ET.parse(fp)

namespace = "{http://webservices.amazon.com/AWSECommerceService/2008-08-19}"
e = element.findall('{0}Items/{0}Item/{0}ItemAttributes/{0}ListPrice/{0}Amount'.format(namespace))
for i in e:
    print i.text

両方とも以下を出力します:

2260

おすすめ記事