pretty code

2019年11月20日 星期三

Parsing XML that hast namespace in python


import xml.etree.ElementTree as ET

def main():
    tree = ET.parse('content.opf')
    root = tree.getroot()

    ns = {
        'manifest' : 'http://www.idpf.org/2007/opf',
        'item' : 'http://www.idpf.org/2007/opf'
    }

    manifest = root.find('manifest:manifest', ns)

    count = 0
    for item in manifest.findall('item:item', ns):
        s = item.attrib
        print(s['href'])
        count += 1

    print('All items are', count)

if __name__ == '__main__':
    main()

沒有留言: