【发布时间】:2019-03-23 10:38:51
【问题描述】:
帮助,我有以下 XML 文件,我正在尝试从中读取和提取数据,下面是 xml 文件的摘录,
<Variable name="Inboard_ED_mm" state="Output" type="double[]">17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154<Properties><Property name="index">25</Property><Property name="description"></Property><Property name="upperBound">0</Property><Property name="hasUpperBound">false</Property><Property name="lowerBound">0</Property><Property name="hasLowerBound">false</Property><Property name="units"></Property><Property name="enumeratedValues"></Property><Property name="enumeratedAliases"></Property><Property name="validity">true</Property><Property name="autoSize">true</Property><Property name="userSlices"></Property></Properties></Variable>
我正在尝试提取以下内容,17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154
我已经完成了这里的示例 xml.etree.ElementTree — The ElementTree XML API 并且我可以让示例工作,但是当我修改上述 xml 的代码时,代码什么也没有返回!
这是我的代码,
import xml.etree.ElementTree as ET
work_dir = r"C:\Temp\APROCONE\Python"
with open(model.xml, 'rt') as f:
tree = ET.parse(f)
root = tree.getroot()
for Variable in root.findall('Variable'):
type = Variable.find('type').text
name = Variable.get('name')
print(name, type)
有什么想法吗?提前感谢您的帮助。
编辑: 感谢所有发表评论的人。在你的建议下,我玩了一会,搜索了一下,得到了以下代码,
with open(os.path.join(work_dir, "output.txt"), "w") as f:
for child1Tag in root.getchildren():
for child2Tag in child1Tag.getchildren():
for child3Tag in child2Tag.getchildren():
for child4Tag in child3Tag.getchildren():
for child5Tag in child4Tag.getchildren():
name = child5Tag.get('name')
if name == "Inboard_ED_mm":
print(child5Tag.attrib, file=f)
print(name, file=f)
print(child5Tag.text, file=f)
要返回以下内容,
{'name': 'Inboard_ED_mm', 'state': 'Output', 'type': 'double[]'}
Inboard_ED_mm
17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154, 17.154
我知道,不是世界上最好的代码,任何关于如何简化代码的想法都非常受欢迎。
【问题讨论】:
-
“下面是 xml 文件的摘录” - 问题可能是
Variable在默认命名空间中。您是否在 XML 中未显示的任何位置有xmlns="???"? -
@Daniel Haley,感谢您的回复,抱歉,我在文件中找不到“xmlns”。
标签: python python-3.x xml-parsing elementtree xml.etree