在Python中我试图导航XML(节点)并根据您处理的最后一个节点创建链接/遍历节点,我有一组源节点和目标节点,我必须从源到目标遍历然后从目标到源,然后再次相同,它可能具有相同的节点倍数倍。
附上下面的XML结构
targetNode="FCMComposite_1_2" sourceNode="FCMComposite_1_1"
targetNode="FCMComposite_1_4" sourceNode="FCMComposite_1_5"
targetNode="FCMComposite_1_6" sourceNode="FCMComposite_1_5"
targetNode="FCMComposite_1_8" sourceNode="FCMComposite_1_2"
targetNode="FCMComposite_1_2" sourceNode="FCMComposite_1_9"
targetNode="FCMComposite_1_3" sourceNode="FCMComposite_1_8"
targetNode="FCMComposite_1_5" sourceNode="FCMComposite_1_3"
在上面的XML中,我必须从第一个SourceNode(FCMComposite_1_1)开始到第一个TargetNode(FCMComposite_1_2),然后我必须从这个TargetNode(Last Node)导航到具有相同值的SourceNode,在这种情况下第4行,然后从那里到目标节点,依此类推。
实现这一目标的最佳方法是什么? Graph是一个很好的选择,我在Python中尝试这个。有人可以帮助我吗?
答案 0 :(得分:0)
您可以使用字典来存储连接。您发布的内容实际上并不是XML,因此我只使用re
来解析它,但您可以采用不同的方式进行解析。
import re
data = '''
targetNode="FCMComposite_1_2" sourceNode="FCMComposite_1_1"
targetNode="FCMComposite_1_4" sourceNode="FCMComposite_1_5"
targetNode="FCMComposite_1_6" sourceNode="FCMComposite_1_5"
targetNode="FCMComposite_1_8" sourceNode="FCMComposite_1_2"
targetNode="FCMComposite_1_2" sourceNode="FCMComposite_1_9"
targetNode="FCMComposite_1_3" sourceNode="FCMComposite_1_8"
targetNode="FCMComposite_1_5" sourceNode="FCMComposite_1_3"
'''
beginning = None
connections = {}
for line in data.split('\n'):
m = re.match(r'targetNode="([^"]+)" sourceNode="([^"]+)"', line)
if m:
target = m.group(1)
source = m.group(2)
if beginning is None:
beginning = source
connections[source] = target
print('Starting at', beginning)
current = beginning
while current in connections.keys():
print(current, '->', connections[current])
current = connections[current]
输出:
Starting at FCMComposite_1_1
FCMComposite_1_1 -> FCMComposite_1_2
FCMComposite_1_2 -> FCMComposite_1_8
FCMComposite_1_8 -> FCMComposite_1_3
FCMComposite_1_3 -> FCMComposite_1_5
FCMComposite_1_5 -> FCMComposite_1_6
我不确定FCMComposite_1_5
的多个目标应该发生什么。