This repository has been archived on 2026-03-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
TP-BDD2/python/personne.py
2022-03-05 21:48:39 +01:00

56 lines
1.6 KiB
Python

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())