Análise de XML

../_images/33888714601_a1f7d020a2_k_d.jpg

untangle

untangle é uma biblioteca simples que recebe um documento XML e retorna um objeto Python contendo os nós e atributos em sua estrutura.

Por exemplo, um arquivo XML como este:

<?xml version="1.0"?>
<root>
    <child name="child1">
</root>

pode ser carregado assim:

import untangle
obj = untangle.parse('path/to/file.xml')

and then you can get the child element’s name attribute like this:

obj.root.child['name']

untangle also supports loading XML from a string or a URL.

xmltodict

xmltodict is another simple library that aims at making XML feel like working with JSON.

Um arquivo XML como este:

<mydocument has="an attribute">
  <and>
    <many>elements</many>
    <many>more elements</many>
  </and>
  <plus a="complex">
    element as well
  </plus>
</mydocument>

pode ser carregado em um dicionário Python como este:

import xmltodict

with open('path/to/file.xml') as fd:
    doc = xmltodict.parse(fd.read())

and then you can access elements, attributes, and values like this:

doc['mydocument']['@has'] # == u'an attribute'
doc['mydocument']['and']['many'] # == [u'elements', u'more elements']
doc['mydocument']['plus']['@a'] # == u'complex'
doc['mydocument']['plus']['#text'] # == u'element as well'

xmltodict also lets you roundtrip back to XML with the unparse function, has a streaming mode suitable for handling files that don’t fit in memory, and supports XML namespaces.