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

Contribuez Python Discussion :

Analyseur générique DataContentHandler basé sur xml.sax.ContentHandler


Sujet :

Contribuez Python

  1. #1
    Invité
    Invité(e)
    Par défaut Analyseur générique DataContentHandler basé sur xml.sax.ContentHandler
    Bonjour,

    Je vous propose aujourd'hui une soluce générique pour dumper vos fichiers XML sous forme de données XML brutes via un analyseur fait maison : DataContentHandler

    Le code Python2 en question :

    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
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from __future__ import unicode_literals
     
    import xml.sax
     
    class Element:
        def __init__ (self, tag, attributes):
            self.tag = str(tag)
            self.attributes = attributes
            self.cdata = ""
            self.children = []
        # end def
    # end class
     
    class DataContentHandler (xml.sax.ContentHandler):
     
        def __init__ (self):
            self.parents = []
            self.root_node = None
        # end def
     
        def startElement (self, tag, attributes):
            "opening XML element tag"
            # element inits
            element = Element(tag, attributes)
            # element is root node ?
            if not self.parents:
                self.root_node = element
                self.parents.append(self.root_node)
            # child element
            else:
                # get last registered parent element
                parent = self.parents[-1]
                # add new child element to parent element
                parent.children.append(element)
                # now child element becomes
                # a potential parent for
                # further children elements
                self.parents.append(element)
            # end if
        # end def
     
        def endElement (self, tag):
            "closing XML element tag"
            # pop last registered parent from LIFO stack
            if self.parents:
                self.parents.pop(-1)
            # end if
        # end def
     
        def characters (self, content):
            "CDATA encountered on the run"
            # get last registered parent element
            parent = self.parents[-1]
            # add CDATA char string to this element
            parent.cdata = content.strip() # strip useless chars
        # end def
     
        def dump (self, element=None, show_all=False):
            "showing element's contents"
            # got no initial element?
            if not element:
                # set to root node
                element = self.root_node
            # end if
            # browse element's children
            for child in element.children:
                # shortcut inits
                _tag = child.tag.capitalize()
                _attrs = child.attributes
                # print tag and cdata only
                if show_all or child.cdata:
                    print "{0}: '{1}'".format(_tag, child.cdata)
                # print tag if got some attrs to show up
                elif _attrs.getLength():
                    print "{0}:".format(_tag)
                # end if
                # showing attributes
                for attribute in _attrs.getNames():
                    print " |---> {0}: '{1}'"\
                        .format(attribute, _attrs.getValue(attribute))
                # end for
                # then recursively dump child's children and so on
                self.dump(child, show_all)
            # end for
        # end def
    # end class DataContentHandler
     
    if __name__ == "__main__":
     
        # handler init
        handler = DataContentHandler()
     
        # parsing file
        xml.sax.parse("example.xml", handler)
     
        # change 'show_all' flag
        # to meet your needs (True or False)
        handler.dump(show_all=True)
     
    # end if
    Exemple de fichier example.xml à créer à côté du script Python :

    Code XML : 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
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <entreprise name="Computer Artists Inc.">
            <staff department="software">
                <employee>
                    <first-name>Nicole</first-name>
                    <last-name>Cavère</last-name>
                    <address>
                        <street>Rue des grottes</street>
                        <zipcode>01234</zipcode>
                        <city>Troglodyteville</city>
                    </address>
                </employee>
                <employee first-name="Phil" last-name="Ozoff" age="354">
                    <skills>
                        <skill type="knowledge/scientific"/>
                        <skill>running fast when work has to be done!</skill>
                    </skills>
                </employee>
                <employee>
                    <id>Mélusine Enfayitte</id>
                    <status type="temporary">congé maternité</status>
                </employee>
            </staff>
        </entreprise>
    </root>

    Amusez-vous bien !

    @+.
    Dernière modification par Invité ; 08/08/2014 à 08h35. Motif: coloration syntaxique code XML

Discussions similaires

  1. [CR 2008] Report basé sur XML/Web Service et dataset
    Par chrbruno dans le forum SDK
    Réponses: 0
    Dernier message: 18/10/2012, 10h58
  2. CMS ou Portail basé sur XML
    Par php_de_travers dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 2
    Dernier message: 08/11/2006, 20h02
  3. menu js, basé sur un fichier xml
    Par nagty dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 26/09/2006, 11h17
  4. XML SAX et eVC++ sur PocketPC
    Par gbardy dans le forum MFC
    Réponses: 2
    Dernier message: 06/07/2006, 17h36
  5. Question moteur de recherche basé sur XML
    Par Royd938 dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 2
    Dernier message: 04/05/2006, 12h00

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