Remove whitespaces in XML string

The easiest solution is probably using lxml, where you can set a parser option to ignore white space between elements: >>> from lxml import etree >>> parser = etree.XMLParser(remove_blank_text=True) >>> xml_str=””‘<root> >>> <head></head> >>> <content></content> >>> </root>”’ >>> elem = etree.XML(xml_str, parser=parser) >>> print etree.tostring(elem) <root><head/><content/></root> This will probably be enough for your needs, but … Read more

Can ElementTree be told to preserve the order of attributes?

With help from @bobince’s answer and these two (setting attribute order, overriding module methods) I managed to get this monkey patched it’s dirty and I’d suggest using another module that better handles this scenario but when that isn’t a possibility: # ======================================================================= # Monkey patch ElementTree import xml.etree.ElementTree as ET def _serialize_xml(write, elem, encoding, qnames, … Read more

XML Parsing: Element Tree (etree) vs. minidom [duplicate]

DOM and Sax interfaces for XML parsing are the classic ways to work with XML. Python had to provide those interfaces because they are well-known and standard. The ElementTree package was intended to provide a more Pythonic interface. It is all about making things easier for the programmer. Depending on your build, each of those … Read more

Faithfully Preserve Comments in Parsed XML

Tested with Python 2.7 and 3.5, the following code should work as intended. #!/usr/bin/env python # CommentedTreeBuilder.py from xml.etree import ElementTree class CommentedTreeBuilder(ElementTree.TreeBuilder): def comment(self, data): self.start(ElementTree.Comment, {}) self.data(data) self.end(ElementTree.Comment) Then, in the main code use parser = ElementTree.XMLParser(target=CommentedTreeBuilder()) as the parser instead of the current one. By the way, comments work correctly out of … Read more

How to get all sub-elements of an element tree with Python ElementTree?

All sub-elements (descendants) of elem: all_descendants = list(elem.iter()) A more complete example: >>> import xml.etree.ElementTree as ET >>> a = ET.Element(‘a’) >>> b = ET.SubElement(a, ‘b’) >>> c = ET.SubElement(a, ‘c’) >>> d = ET.SubElement(a, ‘d’) >>> e = ET.SubElement(b, ‘e’) >>> f = ET.SubElement(d, ‘f’) >>> g = ET.SubElement(d, ‘g’) >>> [elem.tag for elem … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)