[英]Python 3 xml parsing and printing problem
我有一个样本 xml 文件如下
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--Created with JFLAP 7.1.--><structure>
<type>fa</type>
<automaton>
<!--The list of states.-->
<state id="0" name="q1">
<x>104.0</x>
<y>149.0</y>
<initial/>
</state>
<state id="1" name="q2">
<x>210.0</x>
<y>153.0</y>
<final/>
</state>
<state id="2" name="q3">
<x>292.0</x>
<y>155.0</y>
</state>
<!--The list of transitions.-->
<transition>
<from>0</from>
<to>0</to>
<read>0</read>
</transition>
<transition>
<from>1</from>
<to>1</to>
<read>1</read>
</transition>
<transition>
<from>0</from>
<to>1</to>
<read>1</read>
</transition>
<transition>
<from>2</from>
<to>1</to>
<read>0</read>
</transition>
<transition>
<from>1</from>
<to>2</to>
<read>0</read>
</transition>
<transition>
<from>2</from>
<to>1</to>
<read>1</read>
</transition>
</automaton>
</structure>
我正在尝试打印state
标签的所有name
属性,除了id
到目前为止,这是我的代码:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for automaton in root.findall('automaton'):
state = automaton.find('state')
state_name = state.get('name')
print(state_name)
我当前的 output:
q1
我的预期 output:
q1
q2
q3
我很困惑,因为我代码中的for
循环不会打印所有name
属性吗? 我哪里做错了,我该如何解决? 谢谢~
您的代码中缺少另一个findall
。 有多个state
标签。
请参阅下面的代码。 (我用文本 io 缓冲区替换了一个文件。)
xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--Created with JFLAP 7.1.--><structure>
<type>fa</type>
<automaton>
<!--The list of states.-->
<state id="0" name="q1">
<x>104.0</x>
<y>149.0</y>
<initial/>
</state>
<state id="1" name="q2">
<x>210.0</x>
<y>153.0</y>
<final/>
</state>
<state id="2" name="q3">
<x>292.0</x>
<y>155.0</y>
</state>
<!--The list of transitions.-->
<transition>
<from>0</from>
<to>0</to>
<read>0</read>
</transition>
<transition>
<from>1</from>
<to>1</to>
<read>1</read>
</transition>
<transition>
<from>0</from>
<to>1</to>
<read>1</read>
</transition>
<transition>
<from>2</from>
<to>1</to>
<read>0</read>
</transition>
<transition>
<from>1</from>
<to>2</to>
<read>0</read>
</transition>
<transition>
<from>2</from>
<to>1</to>
<read>1</read>
</transition>
</automaton>
</structure>"""
from io import StringIO
import xml.etree.ElementTree as ET
xml_file = StringIO(xml)
tree = ET.parse(xml_file)
root = tree.getroot()
for automaton in root.findall('automaton'):
for state in automaton.findall('state'): # find all the 'state' tags
state_name = state.get('name')
print(state_name)
OUTPUT:
q1
q2
q3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.