diff --git a/src/pylhe/__init__.py b/src/pylhe/__init__.py index 5bcfdef3..ae8f6108 100644 --- a/src/pylhe/__init__.py +++ b/src/pylhe/__init__.py @@ -228,6 +228,25 @@ def mothers(self): ] +def _indent(elem, level=0): + """ + XML indentation helper from https://stackoverflow.com/a/33956544. + """ + i = "\n" + level * " " + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = i + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + _indent(elem, level + 1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + class LHEInit(dict): """Store the block as dict.""" @@ -252,7 +271,7 @@ def tolhe(self): weightgroup_elem, "weight", **value["attrib"] ) weight_elem.text = value["name"] - ET.indent(root, " ") + _indent(root) sweightgroups = ET.tostring(root, encoding="unicode", method="xml") return ( @@ -262,7 +281,6 @@ def tolhe(self): + "\n".join([p.tolhe() for p in self["procInfo"]]) + "\n" + f"{sweightgroups}" - + "\n" # + f" \n" + "" )