我有一个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))
但代码不起作用。它似乎找不到子元素“特征”
提前谢谢
python代码是正确的,但原始xml文件存在语法缺陷。正确的版本应如下所示(属性的右括号“>;”的位置):
显然,elementtree会默默地解析它
相关问题 更多 >
编程相关推荐