PythonXML - mwicat/personal GitHub Wiki

Parse

import xml.etree.cElementTree as etree

root = etree.fromstring(file_content)
tracks = proj.findall('.//AudioTrack')

track_group_id = track.find('./TrackGroupId').attrib['Value']

Node to xml

print(etree.tostring(node, encoding='utf8', method='xml'))

Iterate children

for child in node.getchildren()

Reformat

from xml.dom.minidom import Node, parseString


def remove_blanks(node):
    for x in node.childNodes:
        if x.nodeType == Node.TEXT_NODE:
            if x.nodeValue:
                x.nodeValue = x.nodeValue.strip()
        elif x.nodeType == Node.ELEMENT_NODE:
            remove_blanks(x)


def prettify_xml(xml_string):
        xml = parseString(xml_string)
        remove_blanks(xml)
        xml.normalize()
        return = xml.toprettyxml(indent='  ')