【发布时间】:2019-09-24 22:45:58
【问题描述】:
我正在尝试使用 xml.etree 解析以下 xml 文件。但是,它不会产生任何结果。
from xml.etree import cElementTree as ET
xmlstr = """<?xml version='1.0' encoding='UTF-8'?>
<tns:getCamerasResponse xmlns:tns="https://infoconnect.highwayinfo.govt.nz/schemas/camera2">
<tns:camera>
<tns:description>North along Sth Wstn Mwy from May Rd</tns:description>
<tns:direction>Northbound</tns:direction>
<tns:group>NA</tns:group>
<tns:id>653</tns:id>
<tns:imageUrl>http://www.trafficnz.info/camera/653.jpg</tns:imageUrl>
<tns:lat>-36.90943</tns:lat>
<tns:lon>174.73442</tns:lon>
<tns:name>SH20 May Rd Overbridge</tns:name>
<tns:offline>false</tns:offline>
<tns:region>Auckland</tns:region>
<tns:thumbUrl>http://www.trafficnz.info/camera/thumb/653.jpg</tns:thumbUrl>
<tns:underMaintenance>false</tns:underMaintenance>
<tns:viewUrl>http://www.trafficnz.info/camera/view/653</tns:viewUrl>
</tns:camera>
</tns:getCamerasResponse>"""
root = ET.fromstring(xmlstr)
results = root.findall('tns:camera', {'tns':"https://infoconnect.highwayinfo.govt.nz/schemas/camera2"})
for camera in results:
region = camera.find('tns:region')
if region is not None:
print(region.text)
【问题讨论】:
-
您缺少我认为
results = root.findall('ns:camera', {'ns':"https://infoconnect.highwayinfo.govt.nz/schemas/camera2"})应该可以工作的命名空间 -
有问题的标签不是
<camera>——它是<tns:camera>,你没有考虑到这一点。阅读 xml 命名空间。 -
@Manuel:添加了这个“results = root.findall('tns:camera', {'tns':"infoconnect.highwayinfo.govt.nz/schemas/camera2"})”。仍然给出空结果。
-
results = root.findall('tns:camera', {'tns':"https://infoconnect.highwayinfo.govt.nz/schemas/camera2"})为我工作 -
@Manuel:我在添加命名空间后编辑了代码。我仍然没有得到任何结果。可以请发布您的代码作为答案吗?谢谢。
标签: python xml-parsing xml.etree