From 61bc4fdd82a04da73aa61a5416ac2fa65fb9e237 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Tue, 3 Dec 2013 00:02:50 +0000 Subject: Add parsing of relationships XML --- mammoth/docx/relationships_xml.py | 19 ++++++++++++++++--- tests/docx/relationships_xml_tests.py | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 tests/docx/relationships_xml_tests.py diff --git a/mammoth/docx/relationships_xml.py b/mammoth/docx/relationships_xml.py index 75069fc..bb9c3ed 100644 --- a/mammoth/docx/relationships_xml.py +++ b/mammoth/docx/relationships_xml.py @@ -1,3 +1,6 @@ +import collections + + class Relationships(object): def __init__(self, relationships): self._relationships = relationships @@ -5,6 +8,16 @@ class Relationships(object): def __getitem__(self, key): return self._relationships[key] -class Relationship(object): - def __init__(self, target): - self.target = target + +Relationship = collections.namedtuple("Relationship", ["target"]) + + +def read_relationships_xml_element(element): + children = element.find_children("relationships:Relationship") + return Relationships(dict(map(_read_relationship, children))) + + +def _read_relationship(element): + relationship_id = element.attributes["Id"] + relationship = Relationship(target=element.attributes["Target"]) + return relationship_id, relationship diff --git a/tests/docx/relationships_xml_tests.py b/tests/docx/relationships_xml_tests.py new file mode 100644 index 0000000..7e24491 --- /dev/null +++ b/tests/docx/relationships_xml_tests.py @@ -0,0 +1,21 @@ +from nose.tools import istest, assert_equal + +from mammoth.docx.xmlparser import element as xml_element +from mammoth.docx.relationships_xml import \ + read_relationships_xml_element, Relationships, Relationship + + +@istest +def target_is_read_from_relationship_element(): + element = xml_element("relationships:Relationships", {}, [ + xml_element("relationships:Relationship", { + "Id": "rId8", + "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", + "Target": "http://example.com", + }) + ]) + relationships = read_relationships_xml_element(element) + assert_equal( + Relationship(target="http://example.com"), + relationships["rId8"], + ) -- cgit v1.2.3