gpt4 book ai didi

python - 在 ElementTree 中使用 XPath

转载 作者:IT老高 更新时间:2023-10-28 21:50:48 25 4
gpt4 key购买 nike

我的 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) element 只包含根元素,而不是递归地包含整个文档。它的类型是 Element 而不是 ElementTree。

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 的替代修复:

否则,您需要在搜索字符串中为每个元素指定 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

关于python - 在 ElementTree 中使用 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1319385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com