使用python访问xml文件中的值


<root>
<body>
<structure>
<matrix name="abc">
<def>
<item name="name1" />
<item name="name2" />
</def>
</matrix>
<matrix name="def">
<def>
<item name="name3" />
<item name="name4" />
</def>
<options>
<option par1="okay" par2="bye" par3="hello" />
<option par1="wrong" par2="how are you" par3="im fine" />
</options>
</matrix>
</structure>
</body>
</root>

我一直在尝试访问<options>节点,特别是它的属性(par1,par2,par3)。

如何使用Python实现此操作?我一直在尝试xml.etree.ElementTree

import xml.etree.ElementTree as ET
root = ET.fromstring(xml)
for matrix in root.find('body').find('structure'):
options = matrix.find('options')
if options:
for option in options:
print(option.attrib['par1'])
print(option.attrib['par2'])
print(option.attrib['par3'])

您可以跟随路径到option并使用.attrib来获取属性。或者,直接使用层次路径find元素:

for options in root.find('body/structure/matrix/options'):
for option in options:
print(option.attrib['...'])

最新更新