Python xml
Apparence
Bases
from lxml import etree
tree = etree.parse('mon_fichier.xml')
root = tree.getroot()
print(root.tag) # root
if len(root): # test if it has children
print("The root element has children")
for child in root:
print(child.tag)
for node2 in root.findall('node1/node2'):
node3 = node2.find('node3')
if node3.text == 'xxx':
node33 = etree.SubElement(node2, 'node33')
node33.text = '33'
tree.write('output.xml', xml_declaration=True, encoding='utf-8', pretty_print=True)
else:
continue
|
XPath
# retourne un tableau de résultats
nodes = root.xpath('node1/node2[text()="texte"]')
if len(nodes) == 1:
parent = nodes[0].getparent()
|
Création d'éléments
node1 = etree.SubElement(root, 'node1')
node1.text = 'texte'
tree.write('fichier.xml', xml_declaration=True, encoding='utf-8', pretty_print=True)
|
pretty print
print(etree.tostring(root, pretty_print=True))
# dans un fichier
parser = etree.XMLParser(remove_blank_text=True) # reset de l'indentation du fichier d'origine
tree = etree.parse('fichier.xml', parser)
tree.write('output.xml', xml_declaration=True, encoding='utf-8', pretty_print=True)
|
![]() |
Why doesn't the pretty_print option reformat my XML output? |
ElementTree vs lxml
- ElementTree est la bibliothèque xml par défault
- lxml est une bibliothèque plus riche pour xml et html
# pour ElementTree
import xml.etree.ElementTree as ET
tree = ET.parse('fichier.xml')
# pour lxml
from lxml import etree
tree = etree.parse('fichier.xml')
|