如何解决如何从xml文件访问elementtree数据库中特定元素的子元素
我有一个如下所示的 XML 文件:
<Cars>
<Car vin="1"
label="Ford"
<features>
layout="hatchback"
color="red"
</features>
</Car>
<Car vin="2"
label="GM"
<features>
layout="4door"
color="blue"
</features>
</Car>
</Cars>
我想获得带有 vin==2 的汽车的 features 子元素:
import xml.etree.ElementTree as ET
tree = ET.parse(xmlFile)
root = tree.getroot()
for car in root.findall("Car"):
` vin = car.get("vin")
features = list()
if vin == "2":
features = car.find("features")
color = features.get("color")
print("color is {}".format(color))
但是代码不起作用。貌似找不到子元素“features”
提前致谢
解决方法
python 代码是正确的,但原始 xml 文件有语法缺陷。正确的版本应该如下(属性的右括号“>”的位置):
<Cars>
<Car vin="1"
label="Ford" >
<features
layout="hatchback"
color="red">
</features>
</Car>
<Car vin="2"
label="GM">
<features
layout="4door"
color="blue">
</features>
</Car>
</Cars>
显然 elementtree 会默默地解析它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。