python - 元素树 - 搜索特定元素值而不循环
问题描述
我有一个 xml 文件,其中包含一堆重复的 xml 块。仅当报价具有特定SellerId
且我的商品具有SubCondtion='New'
. 我现在可以通过遍历报价并根据OfferSellerId
我的卖家ID检查xml块中Subcondition = 'New'
的仅使用元素树逻辑而不是在每个报价上循环。ListingPrice
find
findall
SellerId
SubCondition
<Offer>
当前代码
for offer in root.findall('./NotificationPayload/AnyOfferChangedNotification/Offers/'):
OfferSellerId = offer.find('SellerId').text
SubCondition = offer.find('SubCondition').text
if (SellerId == OfferSellerId && SubCondition == 'New'):
ListingPrice = offer.find('ListingPrice/Amount').text
xml
.......
<Offers>
<Offer>
<SellerId>A2LZYV</SellerId>
<SubCondition>new</SubCondition>
<SellerFeedbackRating>
<SellerPositiveFeedbackRating>100</SellerPositiveFeedbackRating>
<FeedbackCount>929</FeedbackCount>
</SellerFeedbackRating>
<ShippingTime minimumHours="24" maximumHours="48" availabilityType="NOW"/>
<ListingPrice>
<Amount>16.69</Amount>
<CurrencyCode>USD</CurrencyCode>
</ListingPrice>
<Shipping>
<Amount>0.00</Amount>
<CurrencyCode>USD</CurrencyCode>
</Shipping>
<ShipsFrom>
<Country>US</Country>
<State>FL</State>
</ShipsFrom>
<IsFulfilledByAmazon>false</IsFulfilledByAmazon>
<IsBuyBoxWinner>false</IsBuyBoxWinner>
<PrimeInformation>
<IsPrime>false</IsPrime>
<IsNationalPrime>false</IsNationalPrime>
</PrimeInformation>
<IsFeaturedMerchant>true</IsFeaturedMerchant>
<ShipsDomestically>true</ShipsDomestically>
</Offer>
......
解决方案
即使ElementTree 对 XPath 的支持有限,它也应该足以做你想做的事......
XML 输入(test.xml)
<doc>
<NotificationPayload>
<AnyOfferChangedNotification>
<Offers>
<Offer>
<SellerId>A2LZYV</SellerId>
<SubCondition>new</SubCondition>
<SellerFeedbackRating>
<SellerPositiveFeedbackRating>100</SellerPositiveFeedbackRating>
<FeedbackCount>929</FeedbackCount>
</SellerFeedbackRating>
<ShippingTime minimumHours="24" maximumHours="48" availabilityType="NOW"/>
<ListingPrice>
<Amount>16.69</Amount>
<CurrencyCode>USD</CurrencyCode>
</ListingPrice>
<Shipping>
<Amount>0.00</Amount>
<CurrencyCode>USD</CurrencyCode>
</Shipping>
<ShipsFrom>
<Country>US</Country>
<State>FL</State>
</ShipsFrom>
<IsFulfilledByAmazon>false</IsFulfilledByAmazon>
<IsBuyBoxWinner>false</IsBuyBoxWinner>
<PrimeInformation>
<IsPrime>false</IsPrime>
<IsNationalPrime>false</IsNationalPrime>
</PrimeInformation>
<IsFeaturedMerchant>true</IsFeaturedMerchant>
<ShipsDomestically>true</ShipsDomestically>
</Offer>
</Offers>
</AnyOfferChangedNotification>
</NotificationPayload>
</doc>
Python
import xml.etree.ElementTree as ET
root = ET.parse("test.xml")
SellerId = "A2LZYV"
for price in root.findall(f".//Offer[SellerId='{SellerId}'][SubCondition='new']/ListingPrice/Amount"):
print(price.text)
打印输出
16.69
推荐阅读
- sql-server - 在SSIS中将excel列从General转换为Date
- awk - 合并某些列匹配的文件
- swift - 如何在 iPhone 开发中添加度数符号作为 UILabel 的一部分?
- google-apps-script - 将 Google 表格导出到云端硬盘
- swift - 使用 Audiokit 录制 MIDI
- python - 熊猫以非标准间隔重新采样
- delphi - 检查 treenode 变量是否引用了已擦除的节点
- android - 永远每20秒拍一张照片
- ruby - VPC 上的 AWS Lambda Ruby - Seahorse::Client::NetworkingError
- python - Sphinx autodoc 无法导入模块