使用etree Python解析xml

2024-03-29 12:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

对于这个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为地址A获取{}。在

这是我的密码

^{pr2}$

得到输出为None,我在这里做了什么错误?在


Tags: cityaddedhereisaddresslocationzipthis
1条回答
网友
1楼 · 发布于 2024-03-29 12:21:04

首先,您的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表达式执行,例如:

^{pr2}$

按以下方式运行:

python2 script.py

这个收益:

^{4}$

相关问题 更多 >