IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

XML vers Class Python


Sujet :

Python

  1. #1
    Membre habitué Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Points : 152
    Points
    152
    Par défaut XML vers Class Python
    Le code XML

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <?xml version="1.0" ?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    	xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    	<soapenv:Body>
    		<AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
    			<identification>TOTO</identification>
    			<date>2017-07-04T15:46:21</date>
    			<type>2</type>
    			<Projet>
    				<Nom>coco</Nom>
    				<Auteur>doudou</Auteur>
    				<type>2</type>
    			</Projet>
    		</AMX>
    	</soapenv:Body>
    </soapenv:Envelope>
    le programme ( non finalisé )


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
     
     
    #-*- coding: utf-8 -*-
     
    import xml.etree.ElementTree as ET
     
    '''
    Created on 12 sept. 2017
     
    @author: eric
    '''
     
    class Projet(object):
        """
         Objet de type Projet  
               contient  nom , auteur et type
        """
     
        def __init__(self, nom , auteur , type):        
             self.nom = nom
             self.auteur = auteur
             self.type = type
        def __str__(self):  
            return "\tnom: {o.nom}\n\tauteur: {o.auteur}\n".format(o=self)
     
     
     
    class Amx(object):
        """
         Objet de type Amx  
               contient  une balise xnls ,
               identificiation
               date
               type 
               x objet Projet 
        """    
        def __init__(self, xnlns , identification , date , type , Projet=[]):
            self.xnlns = xnlns
            self.identification=identification
            self.date= date
            self.type = type
            self.projet = Projet
        def __str__(self):  
            return ("AMX")
     
    #class Soap_env(object):
    #    def __init__(self,   xmlns_soapenv ,xmlns_xsd , xmlns_xsi ,   Soap_body=[]   ):
    #       self.soap_body =Soap_body
     
    class Soap_Body(object):
        def __init__(self, Amx=[]):
            self.Amx = Amx
            '''
            Constructor
            '''
        def __str__(self):  
            return ("Soap_Body")
     
    def parse_projet(node):
        """  
             <Projet>
                 <Nom>coco</Nom>
                 <Auteur>doudou</Auteur>
                 <type>2</type>
             </Projet>
        """  
        p_nom = node.find("Nom").text
        p_auteur = node.find("Auteur").text
        p_type = node.find("type").text
        return Projet(p_nom , p_auteur , p_type)
     
    def parse_amx(node): 
        """
                <AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
                <identification>TOTO</identification>
                <date>2017-07-04T15:46:21</date>
                <type>2</type>
                <Projet> .....
                </Projet>
            </AMX>
            """
        a_xnlns = node.find("xnlns").text
        a_identification =node.find("identification").text
        a_date =node.find("date").text
        a_type = node.find("type").text
        a_projet = [parse_projet(elt) for elt in node.findall("Projet")]
        # recherche les balises Projet
        return Amx(a_xnlns , a_identification , a_date , a_type ,a_projet)
     
     
    def parse_soap_Body(node):     
        """
            <soapenv:Body>
                <AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
           ...
                </AMX>
            </soapenv:Body>  
        """  
        a_body =[parse_projet(elt) for elt in node.findall("soapenv:Body")]
        return Soap_Body(a_body)
     
     
     
    def parse_file(path):
        with open(path, 'r') as fichier:
            tree = ET.ElementTree()
            tree.parse (fichier)
            Soap_env = tree.getroot()
            return [parse_soap_Body(node) for node in Soap_env.findall("soapenv:Envelope")]  
     
     
        if __name__ == "__main__":
            Soap_Bodys = parse_file("ex.xml")
            for f in Soap_Bodys:
                print(f)
    Lorsque je lance ce code direct ou en mode débug avec simplement un point d'arrêt sur la premier ligne il ne se passe rien.

  2. #2
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 823
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 823
    Points : 7 119
    Points
    7 119
    Par défaut
    Bonjour,

    Quelle est la question, problème lié à votre post ci-dessus ?
    Celui qui trouve sans chercher est celui qui a longtemps cherché sans trouver.(Bachelard)
    La connaissance s'acquiert par l'expérience, tout le reste n'est que de l'information.(Einstein)

  3. #3
    Membre habitué Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Points : 152
    Points
    152
    Par défaut
    Citation Envoyé par fred1599 Voir le message
    Bonjour,

    Quelle est la question, problème lié à votre post ci-dessus ?

    LA question est maintenant présent sur le poste.

  4. #4
    Expert éminent
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    3 823
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 3 823
    Points : 7 119
    Points
    7 119
    Par défaut
    à partir de la ligne 112, c'est mal indenté...
    Celui qui trouve sans chercher est celui qui a longtemps cherché sans trouver.(Bachelard)
    La connaissance s'acquiert par l'expérience, tout le reste n'est que de l'information.(Einstein)

  5. #5
    Membre habitué Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Points : 152
    Points
    152
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <?xml version="1.0" ?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    	xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    	<soapenv:Body>
    		<AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
    			<identification>TOTO</identification>
    			<date>2017-07-04T15:46:21</date>
    			<type>2</type>
    			<Projet>
    				<Nom>coco</Nom>
    				<Auteur>doudou</Auteur>
    				<type>2</type>
    			</Projet>
    		</AMX>
    	</soapenv:Body>
    </soapenv:Envelope>
    le programme ( non finalisé )


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
     
     
    #-*- coding: utf-8 -*-
     
    import xml.etree.ElementTree as ET
     
    '''
    Created on 12 sept. 2017
     
    @author: eric
    '''
     
    class Projet(object):
        """
         Objet de type Projet  
               contient  nom , auteur et type
        """
     
        def __init__(self, nom , auteur , type):        
             self.nom = nom
             self.auteur = auteur
             self.type = type
        def __str__(self):  
            return "\tnom: {o.nom}\n\tauteur: {o.auteur}\n".format(o=self)
     
     
     
    class Amx(object):
        """
         Objet de type Amx  
               contient  une balise xnls ,
               identificiation
               date
               type 
               x objet Projet 
        """    
        def __init__(self, xnlns , identification , date , type , Projet=[]):
            self.xnlns = xnlns
            self.identification=identification
            self.date= date
            self.type = type
            self.projet = Projet
        def __str__(self):  
            return ("AMX")
     
    #class Soap_env(object):
    #    def __init__(self,   xmlns_soapenv ,xmlns_xsd , xmlns_xsi ,   Soap_body=[]   ):
    #       self.soap_body =Soap_body
     
    class Soap_Body(object):
        def __init__(self, Amx=[]):
            self.Amx = Amx
            '''
            Constructor
            '''
        def __str__(self):  
            return ("Soap_Body")
     
    def parse_projet(node):
        """  
             <Projet>
                 <Nom>coco</Nom>
                 <Auteur>doudou</Auteur>
                 <type>2</type>
             </Projet>
        """  
        p_nom = node.find("Nom").text
        p_auteur = node.find("Auteur").text
        p_type = node.find("type").text
        return Projet(p_nom , p_auteur , p_type)
     
    def parse_amx(node): 
        """
                <AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
                <identification>TOTO</identification>
                <date>2017-07-04T15:46:21</date>
                <type>2</type>
                <Projet> .....
                </Projet>
            </AMX>
            """
        a_xnlns = node.find("xnlns").text
        a_identification =node.find("identification").text
        a_date =node.find("date").text
        a_type = node.find("type").text
        a_projet = [parse_projet(elt) for elt in node.findall("Projet")]
        # recherche les balises Projet
        return Amx(a_xnlns , a_identification , a_date , a_type ,a_projet)
     
     
    def parse_soap_Body(node):     
        """
            <soapenv:Body>
                <AMX xmlns="https://docs.python.org/3/library/xml.etree.elementtree.html">
           ...
                </AMX>
            </soapenv:Body>  
        """  
        a_body =[parse_projet(elt) for elt in node.findall("soapenv:Body")]
        return Soap_Body(a_body)
     
     
     
    def parse_file(path):
        with open(path, 'r') as fichier:
            print(path)
            tree = ET.ElementTree()
            print(tree)
            print(fichier)
            tree.parse (fichier)
            Soap_env = tree.getroot()
            print(Soap_env)
        return [parse_soap_Body(node) for node in Soap_env.findall("soapenv:Envelope")]  
     
     
     if __name__ == "__main__":
        Soap_Bodys =  parse_file("ex.xml")
        print(Soap_Bodys)
        for f in Soap_Bodys:
            print(f)
    Voici le résultat des print

    ex.xml
    <xml.etree.ElementTree.ElementTree object at 0x00DDD050>
    <_io.TextIOWrapper name='ex.xml' mode='r' encoding='cp1252'>
    <Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at 0x00E27330>
    []


    Maigres la ré-indention du main, le ne retourne que []

    avez-vous une idée?

  6. #6
    Membre confirmé
    Homme Profil pro
    Développeur banc de test
    Inscrit en
    Mai 2014
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur banc de test
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Mai 2014
    Messages : 199
    Points : 482
    Points
    482
    Par défaut
    Bonjour,
    je ne connais pas bien cette librairie mais avant d'essayer de mettre tout ça dans une fonction vous devriez d'abord le tester unitairement, ça sera plus simple.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    if __name__ == "__main__":
        fichier = open("ex.xml", 'r')
        tree = ET.ElementTree()
        tree.parse(fichier)
        Soap_env = tree.getroot()
    Soap_env retourne donc un objet : <Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at ...>

    Soap_env.findall("soapenv:Envelope") retourne bien une liste vide.

    Et en faisant Soap_env.getchildren() on obtient une liste avec un objet : [<Element '{http://schemas.xmlsoap.org/soap/envelope/}Body' at ...>]

  7. #7
    Membre habitué Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Points : 152
    Points
    152
    Par défaut exemple utilsé
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #-*- coding: utf-8 -*-
     
    import xml.etree.ElementTree as ET
     
    if __name__ == "__main__":
        fichier = open("ex.xml", 'r')
        print(fichier)
        tree = ET.ElementTree()
        print(tree)
        tree.parse(fichier)
        Soap_env = tree.getroot()
        print(Soap_env)
        o_Soap_env =  Soap_env.getchildren()
        print(o_Soap_env)
    voici ce que le code exceute
    <_io.TextIOWrapper name='ex.xml' mode='r' encoding='cp1252'>
    <xml.etree.ElementTree.ElementTree object at 0x006EAAF0>
    <Element '{http://schemas.xmlsoap.org/soap/envelope/}Envelope' at 0x02323210>
    [<Element '{http://schemas.xmlsoap.org/soap/envelope/}Body' at 0x0232A960>]

  8. #8
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 287
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 287
    Points : 36 776
    Points
    36 776
    Par défaut
    Salut,

    Lorsque vous recopiez du code, il faut essayer de le comprendre avant de l'adapter à vos besoins.
    Si findall ne trouve rien, il suffit de lire la documentation de findall: elle dit explicitement que çà cherche dans les sous éléments!
    Après vous avez un problème de name space: c'est pas pour rien que les différentes fonctions d'ElementTree l'ont en argument.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  9. #9
    Membre habitué Avatar de dedalios
    Homme Profil pro
    concepteur d'application
    Inscrit en
    Février 2008
    Messages
    495
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Indre et Loire (Centre)

    Informations professionnelles :
    Activité : concepteur d'application
    Secteur : Santé

    Informations forums :
    Inscription : Février 2008
    Messages : 495
    Points : 152
    Points
    152
    Par défaut
    Citation Envoyé par wiztricks Voir le message
    Salut,

    Lorsque vous recopiez du code, il faut essayer de le comprendre avant de l'adapter à vos besoins.
    Si findall ne trouve rien, il suffit de lire la documentation de findall: elle dit explicitement que çà cherche dans les sous éléments!
    Après vous avez un problème de name space: c'est pas pour rien que les différentes fonctions d'ElementTree l'ont en argument.

    - W
    pour information il ne s'agit nullement d'une copie mais d'une adatpation du code d'origine avec un autre cas, justement dans le but de le comprendre.

Discussions similaires

  1. [Mysql] Donnée XML >vers> BDD
    Par largiss dans le forum XQUERY/SGBD
    Réponses: 14
    Dernier message: 28/02/2017, 17h51
  2. [Python 2.X] [PYTHON - ArcPY] Copier-coller classe d'entité vers classe d'entité globale
    Par Falmar dans le forum Général Python
    Réponses: 0
    Dernier message: 27/10/2015, 14h16
  3. [Python 2.7] Parseur XML et classes : optimisation
    Par darkrojo dans le forum Général Python
    Réponses: 0
    Dernier message: 25/05/2011, 21h56
  4. Réponses: 8
    Dernier message: 04/12/2010, 21h51
  5. [XSL-FO] xml vers xsl-fo (pour generation PDF ou RTF)
    Par dams50 dans le forum XSL/XSLT/XPATH
    Réponses: 5
    Dernier message: 13/12/2003, 21h07

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo