Skip to content

Parse data tags of nodes and edges correctly #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 18 additions & 14 deletions pygraphml/graphml_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from __future__ import absolute_import
from __future__ import print_function

import xml.dom
from xml.dom import minidom

from . import Graph
Expand Down Expand Up @@ -63,7 +64,8 @@ def write(self, graph, fname=None):
edge.setAttribute('source', e.node1['label'])
edge.setAttribute('target', e.node2['label'])
if e.directed() != graph.directed:
edge.setAttribute('directed', 'true' if e.directed() else 'false')
edge.setAttribute(
'directed', 'true' if e.directed() else 'false')
for a in e.attributes():
if e != 'label':
data = doc.createElement('data')
Expand Down Expand Up @@ -127,7 +129,7 @@ def parse(self, fname):
"""

g = None
with open( fname, 'r') as f:
with open(fname, 'r') as f:
dom = minidom.parse(f)
root = dom.getElementsByTagName("graphml")[0]
graph = root.getElementsByTagName("graph")[0]
Expand All @@ -143,12 +145,13 @@ def parse(self, fname):
# Get nodes
for node in graph.getElementsByTagName("node"):
n = g.add_node(id=node.getAttribute('id'))

for attr in node.getElementsByTagName("data"):
if attr.firstChild:
n[attr.getAttribute("key")] = attr.firstChild.data
else:
n[attr.getAttribute("key")] = ""
for child in node.childNodes:
if child.nodeType == xml.dom.Node.ELEMENT_NODE and child.tagName == "data":
if child.firstChild:
n[child.getAttribute(
"key")] = child.firstChild.data
else:
n[child.getAttribute("key")] = ""

# Get edges
for edge in graph.getElementsByTagName("edge"):
Expand All @@ -157,12 +160,13 @@ def parse(self, fname):

# source/target attributes refer to IDs: http://graphml.graphdrawing.org/xmlns/1.1/graphml-structure.xsd
e = g.add_edge_by_id(source, dest)

for attr in edge.getElementsByTagName("data"):
if attr.firstChild:
e[attr.getAttribute("key")] = attr.firstChild.data
else:
e[attr.getAttribute("key")] = ""
for child in edge.childNodes:
if child.nodeType == xml.dom.Node.ELEMENT_NODE and child.tagName == "data":
if child.firstChild:
e[child.getAttribute(
"key")] = child.firstChild.data
else:
e[child.getAttribute("key")] = ""

return g

Expand Down