使用 python 访问 xml 文件中的值
Access values in xml file using python
<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'])
您可以按照选项的路径并使用 .attrib
获取属性。或者,直接使用分层路径 find
个元素:
for options in root.find('body/structure/matrix/options'):
for option in options:
print(option.attrib['...'])
<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'])
您可以按照选项的路径并使用 .attrib
获取属性。或者,直接使用分层路径 find
个元素:
for options in root.find('body/structure/matrix/options'):
for option in options:
print(option.attrib['...'])