Skip to content

Commit

Permalink
Fix empty GraphML attribute is not parsed (#7319)
Browse files Browse the repository at this point in the history
* Empty GraphML attribute is not parsed (main branche)

Fixes  #7291

networkx does not parse GraphML attributes that are empty.
This fix will create the attribute with an empty string.

* added test test_graphml.py

* minor changes (lint)
  • Loading branch information
salym committed Mar 1, 2024
1 parent 5934f7e commit c339da9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion networkx/readwrite/graphml.py
Original file line number Diff line number Diff line change
Expand Up @@ -1010,9 +1010,10 @@ def decode_data_elements(self, graphml_keys, obj_xml):
edge_label = data_element.find(f"{pref}EdgeLabel")
if edge_label is not None:
break

if edge_label is not None:
data["label"] = edge_label.text
elif text is None:
data[data_name] = ""
return data

def find_graphml_keys(self, graph_element):
Expand Down
24 changes: 24 additions & 0 deletions networkx/readwrite/tests/test_graphml.py
Original file line number Diff line number Diff line change
Expand Up @@ -1505,3 +1505,27 @@ def test_exception_for_unsupported_datatype_graph_attr():
fh = io.BytesIO()
with pytest.raises(TypeError, match="GraphML does not support"):
nx.write_graphml(G, fh)


def test_empty_attribute():
"""Tests that a GraphML string with an empty attribute can be parsed
correctly."""
s = """<?xml version='1.0' encoding='utf-8'?>
<graphml>
<key id="d1" for="node" attr.name="foo" attr.type="string"/>
<key id="d2" for="node" attr.name="bar" attr.type="string"/>
<graph>
<node id="0">
<data key="d1">aaa</data>
<data key="d2">bbb</data>
</node>
<node id="1">
<data key="d1">ccc</data>
<data key="d2"></data>
</node>
</graph>
</graphml>"""
fh = io.BytesIO(s.encode("UTF-8"))
G = nx.read_graphml(fh)
assert G.nodes["0"] == {"foo": "aaa", "bar": "bbb"}
assert G.nodes["1"] == {"foo": "ccc", "bar": ""}

0 comments on commit c339da9

Please sign in to comment.