Python :在 gxl 文件中查找结束节点(叶)



我有一个 gxl 文件,我想找到它的所有终端节点(叶(并存储每个终端节点名称(在标签节点中,名称属性(。 我意识到在 gxl 文件中,终端节点是具有节点标签但没有边缘标签的节点。

我想找到所有没有任何边缘的节点。

那我该怎么做呢? 这是我的 GXL 文件示例链接: https://gist.github.com/anonymous/61c1afd751214a0473fd62ee74a3b1d6

例如,这里的节点 ID 270 是终端节点,因为它没有任何边缘标记。

<node id="N_270"> 
<attr name="name"> 
<string>
android.content.Context 
java.lang.String getString(int) 
</string> 
</attr>
</node> 
<node id="N_271"> 
<attr name="name"> 
<string>android.view.ViewGroup 
voidinit(android.content.Context,android.util.AttributeSet,int) 
</string> 
</attr> 
</node>
<edge from="N_271" to="N_291" isdirected="true" id="N_271--N_291"> 
</edge> 

考虑使用 Python 标准库中的 xml.etree.ElementTree。

import xml.etree.ElementTree as et
gxl_file_path = "C:\some\file\path\file.gxl"
tree = et.parse(gxl_file_path)
root = tree.getroot()  # At this point you can traverse the node structure as needed

假设您需要查找节点的名称:

>>> root.tag
'gxl'

或者,如果要遍历所有边缘节点:

for edge in root.iter('edge'):
# ... Logic ...

我无法确切地说出您要解析的内容,但我相信您应该迭代"节点"节点,达到这样的程度:

for node in root.iter('node'):
if node.find('attr'):  # If the attribute node is present
name = node.find('attr').get('name')

最新更新