我的程序应该使用DFS函数来搜索XML树并打印输入的那个事件的子节点。到目前为止我遇到的问题是尝试将元素树解析为我的dfs函数将采用的格式。
我的代码:
import xml.etree.ElementTree as ET
tree = ET.ElementTree(file='XMLStuff3.xml')
root = tree.getroot()
def dfs(adjLists, s):
stack = [s]
visited = set()
while stack:
v = stack.pop()
if v in visited:
continue
print(v, " ", end='')
visited.add(v)
yield v
for w in adjLists.get(v, []):
stack.append(w)
# ------------------------------------------------------------------
from xml.etree import ElementTree
with open('XMLStuff3.xml') as f:
tree = ElementTree.parse(f)
for node in tree.iter():
print(node.attrib)
l1 =[]
while True:
event = input("Enter Event (or Enter to quit): ")
if not event:
break
for child in root:
l1 = [ child.attrib['action'] for child in root ]
if any(event in e for e in l1):
dfs(node.attrib, event) #Event is supposed to go into dfs as the root node where the function returns the childs of that node
print("Match", )
else:
print('No Match')
print("Done")
我正在使用的XML文件:
<?xml version="1.0"?>
<root>
<node action="Stay" response="">
<node action="" response="Pause Menu"/>
<node action="" response="Sit"/>
</node>
<node action="Enemy Rushing User" response="">
<node action="" response="Dodge Left"/>
<node action="" response="Dodge Right"/>
</node>
<node action="Move" response="">
<node action="Reverse" response="">
<node action="" response="Back Left"/>
<node action="" response="Back Straight"/>
<node action="" response="Back Middle"/>
</node>
<node action="Forward" response="">
<node action="" response="Forward Left"/>
<node action="" response="Forward Straight"/>
<node action="" response="Forward Right"/>
</node>
</node>
</root>
到目前为止,当我输入类似'Stay'的事件时,它会找到一个匹配项,但下一行的dfs函数不会执行,因为它的格式不正确。函数将采用的格式是我自己尝试和工作的:
adjLists1 = {'0':['One','Two','Three'], '1':['Four'], '2':['Five','Six'], '3':['Seven','Eight'], '4':[],
'5':['Nine','Ten','Eleven'], '6':['Twelve','Thirteen','Fourteen'], '7':[], '8':[]
我的一般问题是如何将xml树解析为该格式?我试过在dfs函数中使用'node.attrib'作为'adjLists'参数,它接近那个格式但还不够。