I need to process a graphml (XML) file created by a yEd graph in order to get the node and edges attributes of that graph. I need to do that using the networkX library. I'm new at Python and I have never used the networkX library so any help would be appreciated.
Asked
Active
Viewed 7,852 times
2 Answers
7
This should get you started...
In yEd create the graph and File > Save As... using the GraphML format. Say, you save it to file 'test.graphml'.
Navigate to that directory and run Python:
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.read_graphml('test.graphml')
>>> nx.draw(G)
>>> plt.show()
>>>
Furthermore, if you want to read and process the attributes of the nodes, you can iterate through them, extracting the data from them like this:
for node in G.nodes(data=True):
print node
This will result in something like this (I created a random graph in yEd to test this):
('n8', {'y': '178.1328125', 'x': '268.0', 'label': '8'})
('n9', {'y': '158.1328125', 'x': '0.0', 'label': '9'})
('n0', {'y': '243.1328125', 'x': '160.0', 'label': '0'})
('n1', {'y': '303.1328125', 'x': '78.0', 'label': '1'})
('n2', {'y': '82.1328125', 'x': '221.0', 'label': '2'})
('n3', {'y': '18.1328125', 'x': '114.0', 'label': '3'})
('n4', {'y': '151.1328125', 'x': '170.0', 'label': '4'})
('n5', {'y': '122.1328125', 'x': '85.0', 'label': '5'})
('n6', {'y': '344.1328125', 'x': '231.0', 'label': '6'})
('n7', {'y': '55.1328125', 'x': '290.0', 'label': '7'})
As a final example, if one wants to access the x coordinate of node n5
, then:
>>> print G['n5']['x']
will give you 85.0
.

daedalus
- 10,873
- 5
- 50
- 71
-
In the current version of yEd Live, saving as a graphML file and then importing into NetworkX 2.x, the node properties are all missing: `('n0', {}) ('n1', {}) ('n2', {})` – Aaron Bramson Feb 20 '20 at 07:56
-
@AaronBramson: yEd Live uses a different (newer) format for item metadata (styling and positional information) compared with yEd Desktop. Both variants are not part of GraphML proper and are custom extensions, but it seems like NetworkX only supports the older yFiles format. – Joey Jul 27 '23 at 11:32
1
I read this question and thought: The doc for that package is REALLY good, even by Python standards. You should really check it out.
IF you have a graph XML file, it looks like it's as easy as:
>>> mygraph=nx.read_gml("path.to.file")
-
@gauden: I meant to imply--the networkX doc is an especially good example of documentation, from a set of especially good examples :) – BenDundee Jun 08 '13 at 19:37
-
thanks! yeah I read the whole tutorial but it only explains the networkx commands not how they interact with xml files, thats what got me confused – geolykos Jun 08 '13 at 22:48