Skip to content
Closed
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions pygeometa/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,15 @@ def pretty_print(xml: str) -> str:
"""

LOGGER.debug('pretty-printing XML')
if isinstance(xml, bytes):
xml = xml.decode('utf-8')

# minidom rejects a bare '&', which appears when MCF text (for
# example a creation date) is interpolated unescaped. Existing
# character and numeric entities are left alone.
xml = re.sub(r'&(?!(?:#\d+|#x[0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]+);)',
'&', xml)

val = minidom.parseString(xml)
return '\n'.join([val for val in val.toprettyxml(indent=' '*2).split('\n') if val.strip()]) # noqa

Expand Down
21 changes: 21 additions & 0 deletions tests/run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,27 @@ def test_pretty_print(self):
self.assertEqual(xml2[-1], '>', 'Expected closing bracket')
self.assertTrue(xml2.startswith('<?xml'), 'Expected XML declaration')

def test_pretty_print_ampersand_in_creation_date(self):
"""bare '&' in a date must not crash pretty-print (#336)"""

iso_os = ISO19139OutputSchema()
mcf = read_mcf(get_abspath('../sample.mcf.yml'))
mcf['metadata']['dates']['creation'] = '2014-11-11 & later'

xml = render_j2_template(mcf, iso_os.template_dir)
self.assertIsInstance(xml, str, 'Expected unicode string')
self.assertIn('&amp;', xml)
self.assertTrue(xml.startswith('<?xml'), 'Expected XML declaration')
self.assertEqual(xml[-1], '>', 'Expected closing bracket')

xml2 = pretty_print('<root>2014-11-11 & later</root>')
self.assertIn('&amp;', xml2)
self.assertNotIn('&amp;amp;', xml2)

already = pretty_print('<root>a &amp; b</root>')
self.assertIn('&amp;', already)
self.assertNotIn('&amp;amp;', already)

def test_get_charstring(self):
"""Test support of unilingual or multilingual value(s)"""

Expand Down
Loading