python - 使用 etree Python 解析 xml

标签 python xml xml-parsing elementtree xml.etree

对于这个 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/

相关文章:

python - 使用 python 解析非常大的 xml 文件时出现问题

python - 在 python 字典中查找匹配 (x,y) 或 (y,x) 的元组

python - 读取.dat文件日期字符串

python - 将元组列表保存到文件时,“ascii”编解码器无法编码字符错误

python - 解压缩 .gz 文件并将其存储在 .tar.gz 存档中

java - Jasper可以编译web.xml中的XML外部实体吗?

Python 和 XML 处理

ruby - 为什么 REXML 不能解析前面有换行符的 CDATA?

python - 将 kickstart 文件传递​​给虚拟管理器 xml 文件

java - 在 java 中使用 xstream 解析 xml (android studio)