from xml.dom import minidom doc = minidom.parse('../xml/TP1.xml') # Affiche l'arbre complet #print(doc.toxml()) # Ou #print(doc.toprettyxml()) # On récupère le noeud personne. personne = doc.getElementsByTagName('personne')[0] def getChildrenByTagName(doc, name): """Une fonction récupérant les fils directs d'un certain type.""" return [c for c in doc.childNodes if c.nodeType == c.ELEMENT_NODE and c.tagName == name] #personne = getChildrenByTagName(doc, 'personne')[0] # Affiche le nom et le prenom de la personne print(personne.getAttribute('nom'), personne.getAttribute('prenom')) # Ou print(personne.attributes['nom'].value, personne.attributes['prenom'].value) # Affiche l'adresse email email = doc.getElementsByTagName('email')[0] email = getChildrenByTagName(personne, 'email')[0] print(email.firstChild.data) # Affiche l'adresse postale ainsi que le code postal adresse = personne.getElementsByTagName('adresse')[0] print(adresse.firstChild.data, adresse.getAttribute('code')) # Acceder à un element inexistant print(doc.getElementsByTagName('test')) # Afficher le contenu de l'attribut data du telephone # personne.getElementsByTagName('phone')[0].data # Lister les methodes du noeud fils de email print(dir(email.firstChild)) # Compter le nombre d'elements du noeud racine print(len(doc.childNodes)) print(doc.childNodes) print(doc.toxml()) # Modifier l'email et afficher le résultat email.firstChild.data = "foo@bar.com" print(doc.toxml()) # Modifier son numero de telephone doc.getElementsByTagName('telephone')[0].attributes['numero'].value = '42' print(doc.toxml())