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

Interfa�age autre langage Python Discussion :

Lecture dun fichier xml avec python


Sujet :

Interfa�age autre langage Python

Vue hybride

Message pr�c�dent Message pr�c�dent   Message suivant Message suivant
  1. #1
    Membre confirm�
    Inscrit en
    Mai 2008
    Messages
    112
    D�tails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 112
    Par d�faut Lecture dun fichier xml avec python
    Salut, chers forumers!
    je suis d�butant en python et aimerais effectuer une lectuere d'un fichier xml dans un repertoire quelconque .
    J'ai recu de mon directeur (je suis etudiant) le code python suivant:

    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
     
    # -*- coding: latin1 -*-
     
    """Script for executing the Unit-Tests in the sourcen.
    """
     
    import os
     
    ################################################################################
    # BuildError
    class BuildError(Exception):
        """Throw an exception, when there is an error while building.
        """
     
    ################################################################################
    # shell_command
    def shell_command(cmd):
        """Start a process and return the process-output as string.
        """
        cmd2 = cmd + ' 2>&1'
        p = os.popen(cmd2)
        lines = []
        line = p.readline()
        while line:
            lines.append(line)
            line = p.readline()
        try:
            status = p.close()
        except KeyboardInterrupt, e:
            raise
        except:
            raise BuildError(''.join(lines))
        if status:
            raise BuildError(''.join(lines))
     
        return lines
     
    ################################################################################
    # execute_config
    def execute_testscripts(path, config):
        """Seach the scripts with end .test.pl, .test.py, .test.bat in the transmitted files and execute it 
           If the returned status ist defferent to 0, the returned value will be add as Error.
           A table ist returned, per testscript an incertion with the error-message.
        """
        messages = {};
        for root, dirs, files in os.walk(path):
            if root.find('.svn') < 0: # nicht die Dateien aus den .svn-Verzeichnissen
                for file in files:
                    cmd = None
                    if file.lower().endswith('.test.pl'):
                        cmd = 'perl.exe '
                    elif file.lower().endswith('.test.py'):
                        cmd = 'python.exe '
                    elif file.lower().endswith('.test.bat'):
                        cmd = 'cmd /C '
                    if cmd:
                        cmd += root + '\\' + file
                        print '%-30s ' % file,
                        try:
                            if 'Debug' in dirs:
                                shell_command('rmdir /S /Q ' + root + '\\Debug')   # Delete all files from last tests
                            shell_command(cmd + ' %s' % config)
                            print 'ok'
                            messages[file] = ''
                        except BuildError, e:
                            print 'Fehler'
                            messages[file] = str(e)
        return messages
     
    ################################################################################
    # main
    def main():
        """The "mainprogramm".
        """
        import sys
        rootpath = sys.argv[1]
     
        messages = execute_testscripts(rootpath, 'Debug')
        text = ''
        has_errors = False
        for file in sorted(messages.keys()):
            status = 'ok'
            if messages[file]:
                status = 'Fehler'
                has_errors = True
            text += '%-30s  %s\n' % (file, status)
            if messages[file]:
                text += '=' * 80 + '\n'
                text += messages[file]
                text += '=' * 80 + '\n\n'
     
        dumpFile = open(sys.argv[2], 'w')
        dumpFile.write(text)
        dumpFile.close()
        return has_errors
     
     
    ################################################################################
    if __name__ == '__main__':
        main()
    J'aimerais, � l�ide de ce code, lire le fichier xml suivant et l'afficher:
    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
     
    <?xml version="1.0" encoding="UTF-8"?><!-- configurationsfile for testrunner.py --><run>    
        <!-- Global setting -->   
        <global>       
            <!-- Path to CA-Installation. This must be a Developer-Installation   inclusivsourcetree ! -->       
            <!-- Path to Visual Studio 2008 -->
            <devenv path="c:\Programme\Microsoft Visual Studio 9.0\Common7\IDE\devenv.com" version="2008"/>
     
            <!-- Who shall be informed about compile-error? -->
            <notify>
                <email name="[email protected]"/>
            </notify>        
        </global>
        <!-- Configuration for the den buildprocess and tests run-->
        <configuration>
            <!-- Pfad zu den Testfällen. -->
            <testcasepath path="D:\Source\Project"/>
     
            <!-- Path, where the protocols and archiv will be save -->
            <output path="D:\Systemtests\CppUnitTestResults"/>
     
            <!-- Tests only in the Debug or Releaseversion or in both? -->
            <runtests>
                <!--<debug /> -->
                <release/>
            </runtests>
     
            <!-- Solutions to compile und VS-version used -->
            <solutionfiles>
    		<solution path="Source\TesselationTest.sln" version="2008"/>
    		<solution path="Source\UtilitiesTest.sln" version="2008"/>
            </solutionfiles>        
        </configuration>
     
        <!-- Files to be tested -->
        <tests>
            <test assembly="BaseMathTest.dll" name="BaseMath" type="CppUnit">
                <notify>
                    <email name="[email protected]"/>
                </notify>
            </test>
     
    	<test assembly="UtilitiesTest.dll" name="Utilities" type="CppUnit">
                <notify>
                    <email name="[email protected]"/>
    	    </notify>
    	</test>
        </tests>
    </run>
    Comment puis-je my prendre? quelqu'un peut t-il me donner une piste, voire un exemple ou bien me faire un code pour cel�?

    Merci d'avance

  2. #2
    Expert �minent
    Homme Profil pro
    Architecte technique retrait�
    Inscrit en
    Juin 2008
    Messages
    21 754
    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 754
    Par d�faut XML est tendance mais il faut un peu de travail.
    Lire le chapitre 9 de "Dive Into Python".
    R�cup�rer les exemples.
    Bon courage
    -W
    Dive Into Python est livr� avec dans l'aide Python de la distribution ActiveState.
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Membre confirm�
    Inscrit en
    Mai 2008
    Messages
    112
    D�tails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 112
    Par d�faut
    Citation Envoy� par wiztricks Voir le message
    Lire le chapitre 9 de "Dive Into Python".
    R�cup�rer les exemples.
    Bon courage
    -W
    Dive Into Python est livr� avec dans l'aide Python de la distribution ActiveState.
    Merci beaucoup!
    J'y ai jet� un coup d'oeil et il me parait tr�s tr�s interessant. Il va s�rement me servir.

  4. #4
    Membre confirm�
    Inscrit en
    Mai 2008
    Messages
    112
    D�tails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 112
    Par d�faut
    Citation Envoy� par merlinerick Voir le message
    Merci beaucoup!
    J'y ai jet� un coup d'oeil et il me parait tr�s tr�s interessant. Il va s�rement me servir.
    Salut, wiztricks!
    Mon probleme maintenat se situe au niveau de comment implementer la fonction qui lit le fichier HML?

    En fait, j'ai fait juste le code de lecture et ca marche. Il me reste maintenent � le inserer ce code dans le fichier que j'ai envoy� precedemment. Je me pose la question de savoir o� est-ce que je pourrais ins�rer cel�? Devrai-je pour cel� faire une fonction propre ou bien...?

    Merci d'avance

  5. #5
    Expert �minent
    Homme Profil pro
    Architecte technique retrait�
    Inscrit en
    Juin 2008
    Messages
    21 754
    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 754
    Par d�faut
    Le bouquin donne en exemple:
    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    5
    >>> from xml.dom import minidom                                          
    >>> xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')  
    >>> xmldoc                                                               
    <xml.dom.minidom.Document instance at 010BE87C>
    >>> print xmldoc.toxml()
    Donc vous savez lire le fichier XML avec une biblioth�que qui permet de parcourir les noeuds et les contenus de la structure.
    Et... si cela est... je ne comprends pas votre question.
    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  6. #6
    Membre confirm�
    Inscrit en
    Mai 2008
    Messages
    112
    D�tails du profil
    Informations forums :
    Inscription : Mai 2008
    Messages : 112
    Par d�faut
    Je lis effectivement le fichier comme le livre le dis. Mon probleme est de savoir s'il faille que j'implemente une fonction dans le code suivant (en fait, je dois lire le fichier xml en utilisant aussi ce code):
    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
     
    # -*- coding: latin1 -*-
     
    """Script for executing the Unit-Tests in the sourcen.
    """
     
    import os
     
    ################################################################################
    # BuildError
    class BuildError(Exception):
        """Throw an exception, when there is an error while building.
        """
     
    ################################################################################
    # shell_command
    def shell_command(cmd):
        """Start a process and return the process-output as string.
        """
        cmd2 = cmd + ' 2>&1'
        p = os.popen(cmd2)
        lines = []
        line = p.readline()
        while line:
            lines.append(line)
            line = p.readline()
        try:
            status = p.close()
        except KeyboardInterrupt, e:
            raise
        except:
            raise BuildError(''.join(lines))
        if status:
            raise BuildError(''.join(lines))
     
        return lines
     
    ################################################################################
    # execute_config
    def execute_testscripts(path, config):
        """Seach the scripts with end .test.pl, .test.py, .test.bat in the transmitted files and execute it 
           If the returned status ist defferent to 0, the returned value will be add as Error.
           A table ist returned, per testscript an incertion with the error-message.
        """
        messages = {};
        for root, dirs, files in os.walk(path):
            if root.find('.svn') < 0: # nicht die Dateien aus den .svn-Verzeichnissen
                for file in files:
                    cmd = None
                    if file.lower().endswith('.test.pl'):
                        cmd = 'perl.exe '
                    elif file.lower().endswith('.test.py'):
                        cmd = 'python.exe '
                    elif file.lower().endswith('.test.bat'):
                        cmd = 'cmd /C '
                    if cmd:
                        cmd += root + '\\' + file
                        print '%-30s ' % file,
                        try:
                            if 'Debug' in dirs:
                                shell_command('rmdir /S /Q ' + root + '\\Debug')   # Delete all files from last tests
                            shell_command(cmd + ' %s' % config)
                            print 'ok'
                            messages[file] = ''
                        except BuildError, e:
                            print 'Fehler'
                            messages[file] = str(e)
        return messages
     
    ################################################################################
    # main
    def main():
        """The "mainprogramm".
        """
        import sys
        rootpath = sys.argv[1]
     
        messages = execute_testscripts(rootpath, 'Debug')
        text = ''
        has_errors = False
        for file in sorted(messages.keys()):
            status = 'ok'
            if messages[file]:
                status = 'Fehler'
                has_errors = True
            text += '%-30s  %s\n' % (file, status)
            if messages[file]:
                text += '=' * 80 + '\n'
                text += messages[file]
                text += '=' * 80 + '\n\n'
     
        dumpFile = open(sys.argv[2], 'w')
        dumpFile.write(text)
        dumpFile.close()
        return has_errors
     
     
    ################################################################################
    if __name__ == '__main__':
        main()
    Faudrait-il ajouter une nouvelle fonction? O� bien dois-je ajouter les lignes (exemple)
    Code : S�lectionner tout - Visualiser dans une fen�tre � part
    1
    2
    3
    4
    from xml.dom import minidom                                          
    xmldoc = minidom.parse('~/diveintopython/common/py/kgp/binary.xml')  
    xmldoc                                                               
    print xmldoc.toxml()
    quelque part dans le lot? Si oui � quel niveau? C'est en fait le probleme que j'ai actuellement.

    Merci d'avance

Discussions similaires

  1. [SAX] Lecture de fichier XML avec l'API SAX
    Par SMinet dans le forum Format d'�change (XML, JSON...)
    R�ponses: 1
    Dernier message: 20/10/2009, 16h19
  2. pickler un fichier XML avec python
    Par Gldev_comp dans le forum G�n�ral Python
    R�ponses: 1
    Dernier message: 10/07/2008, 05h31
  3. Lire un fichier XML avec Python
    Par eyquem dans le forum G�n�ral Python
    R�ponses: 2
    Dernier message: 19/12/2007, 13h54
  4. G�rer un fichier XML avec Python
    Par ffets dans le forum G�n�ral Python
    R�ponses: 25
    Dernier message: 31/10/2007, 14h47
  5. [DOM4J] Probl�me de lecture de fichier xml avec dom4j
    Par santana2006 dans le forum Format d'�change (XML, JSON...)
    R�ponses: 3
    Dernier message: 05/04/2006, 16h52

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