gpt4 book ai didi

python - 使用 etree Python 解析 xml

转载 作者:行者123 更新时间:2023-12-01 05:22:30 25 4
gpt4 key购买 nike

对于这个 xml

<locations>

<location>
<locationid>1</locationid>
<homeID>281</homeID>
<buildingType>Added</buildingType>
<address>A</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
<location>
<locationid>2</locationid>
<homeID>81</homeID>
<buildingType>Added</buildingType>
<address>B</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
.
.
.
.
<location>
<locationid>10</locationid>
<homeID>21</homeID>
<buildingType>Added</buildingType>
<address>Z</address>
<address2>This is address2</address2>
<city>This is city/city>
<state>State here</state>
<zip>1234</zip>
</location>
</locations>

如何使用 etree 获取地址 AlocationID

这是我的代码,

import urllib2
import lxml.etree as ET

url="url for the xml"
xmldata = urllib2.urlopen(url).read()
# print xmldata
root = ET.fromstring(xmldata)
for target in root.xpath('.//location/address[text()="A"]'):
print target.find('LocationID')

获取输出为None,我在这里做错了什么?

最佳答案

首先,您的 xml 格式不正确。您在发布信息时应更加小心,并尽量避免其他用户修复您的数据。

您可以搜索前一个同级,例如:

import urllib2
import lxml.etree as ET

url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
for target in root.xpath('.//location/address[text()="A"]'):
for location in [e for e in target.itersiblings(preceding=True) if e.tag == "locationid"]:
print location.text

或者直接从 xpath 表达式执行,例如:

import urllib2
import lxml.etree as ET

url="..."
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
print root.xpath('.//location/address[text()="A"]/preceding-sibling::locationid/text()')[0]

像这样运行其中一个:

python2 script.py

产量:

1

关于python - 使用 etree Python 解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22007185/

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