Skip to content

Instantly share code, notes, and snippets.

@yeliu84
Created December 15, 2011 17:46
Show Gist options
  • Save yeliu84/1482034 to your computer and use it in GitHub Desktop.
Save yeliu84/1482034 to your computer and use it in GitHub Desktop.
Unprettify XML
#!/bin/python
# works w/Jython also
# http://code.activestate.com/recipes/551778-unprettify-xml-strip-irrelevant-spaces-and-newline/
import xml.dom.minidom as dom
input_xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd"
>
<command>
<login>
<clID>username</clID>
<pw>password</pw>
<options>
<version>1.0</version>
<lang>en</lang>
</options>
<svcs>
<objURI>urn:ietf:params:xml:ns:domain-1.0</objURI>
<objURI>urn:ietf:params:xml:ns:host-1.0</objURI>
</svcs>
</login>
<clTRID>ABC-12345-XYZ</clTRID>
</command>
</epp>"""
"""
Simple doctest:
>>> fromprettyxml(input_xml)
<?xml version="1.0" ?><epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd"><command><login><clID>username</clID><pw>password</pw><options><version>1.0</version><lang>en</lang></options><svcs><objURI>urn:ietf:params:xml:ns:domain-1.0</objURI><objURI>urn:ietf:params:xml:ns:host-1.0</objURI></svcs></login><clTRID>ABC-12345-XYZ</clTRID></command></epp>
"""
def fromprettyxml(input_xml): #cool name, but not the opposite of dom.toprettyxml()
_dom = dom.parseString(input_xml)
output_xml = ''.join([line.strip() for line in _dom.toxml().splitlines()])
_dom.unlink()
return output_xml
def _test():
import doctest, stripxml
doctest.testmod(stripxml)
if __name__ == "__main__":
_test()
print fromprettyxml(input_xml)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment