【发布时间】:2013-02-17 18:57:11
【问题描述】:
因为我正在处理的 XML 文件具有不一致的子元素,所以我在查找和编辑特定子元素时遇到了一些困难,该子元素直到文件的更下方才出现在一系列元素中。 我正在使用 Python 2.7.1 中包含的 Python 的 ElementTree。
这是我正在处理的 XML 文件类型的示例:
<?xml vin="1.0" encoding="UTF-8" standalone="yes"?>
<whatever id='Subaru' YouCanDriveMyCar='Wednesday' transmission='stick'>
<model id='Ford' year='1972'>A</model>
<model id='Chevrolet' vin="1234567890" stereo='Alpine' airconditioning='notworking'>Volt</model>
<model id='Dodge' vin="3456789012" airconditioning='working'>Durango</model>
<model id='Mercedes' vin="4567890123" airconditioning='none'>S150</model>
<model id='BMW'>M350</model>
<model id='Volkswagen' vin="5678901234" stereo='Sony'>Beetle</model>
<model id='Honda' vin="6789012345" airconditioning="blowsicecubes">Accord</model>
</whatever>
在本例中,我想找到模型 id='Volkswagen' 并将 stereo='Sony' 更改为 'Blaupunkt'。
如果我使用 ElementTree 搜索属性“stereo”,则会出错,因为文件顶部的元素中不包含“stereo”。
任何帮助或提示将不胜感激。
【问题讨论】:
标签: python xml xml-parsing elementtree