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

Format d'échange (XML, JSON...) Java Discussion :

Recuperer des nodelist avec xpath


Sujet :

Format d'échange (XML, JSON...) Java

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2014
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Ardèche (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mars 2014
    Messages : 1
    Points : 0
    Points
    0
    Par défaut Recuperer des nodelist avec xpath
    Bonjour à tous, je viens vous voir après plusieurs heures de batailles avec xpath. J'ai une classe me permettant de créer ou d'importer un fichier XML, pour l'import j'utilise xpath, seulement je ne parviens pas à l'utiliser convenablement et fais face à d'étrange problème ( le contenu de mes nodelist).
    Je ne sais pas vraiment quoi vous dire de plus, j'aurais préféré vous poser une question précise mais je suis un peu perdu à vrai dire . du coup je vous copie l’intégralité de mon code..

    La méthode Sauvegarde de ma classe SerialisationXml marche correctement mais au cas ou je l'ai laissé


    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
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    package Xml;
     
    import projettut.*;
    import org.jdom2.output.*;
    import java.io.*;
    import java.util.Collection;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import org.jdom2.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.xpath.*;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
     
    public class SerialisationXML {
     
        //Nous allons commencer notre arborescence en créant la racine XML
        //qui sera ici "sauvegarde".
        static Element racine = new Element("sauvegarde");
     
        //On crée un nouveau Document JDOM basé sur la racine que l'on vient de créer
        static Document document = new Document(racine);
     
     
        Element Enseignants = new Element("Enseignants");
        Element Matieres = new Element("Matieres");
     
        public SerialisationXML() {
        }
     
        public void sauvegardeXml(Conteneur<String, Enseignant> enseignantConteneur, Conteneur<String, Matieres> matiereConteneur) {
            racine = new Element("Sauvegarde");
            document = new Document(racine);
            racine.addContent(Enseignants);
            racine.addContent(Matieres);
     
            int[] tab;
     
            Collection<Enseignant> tree = enseignantConteneur.values();
            for (Enseignant p : tree) {
     
                Element Enseignant = new Element("Enseignant");
                Enseignants.addContent(Enseignant);
     
                Attribute idEnseignant = new Attribute("id", p.getIdEnseignant());
                Enseignant.setAttribute(idEnseignant);
     
                Element nomEnseignant = new Element("nom");
                nomEnseignant.setText(p.getNom());
                Enseignant.addContent(nomEnseignant);
     
                Element prenomEnseignant = new Element("prenom");
                prenomEnseignant.setText(p.getPrenom());
                Enseignant.addContent(prenomEnseignant);
            }
     
            Collection<Matieres> tree2 = matiereConteneur.values();
     
            for (Matieres m : tree2) {
                Element matiere = new Element("Matiere");
                Matieres.addContent(matiere);
     
                Attribute idMatiere = new Attribute("id", m.getIdentifiant());
                matiere.setAttribute(idMatiere);
     
                Element nomMatiere = new Element("Titre");
                nomMatiere.setText(m.getNomMatiere());
                matiere.addContent(nomMatiere);
     
                m.getEnseignant().positionner(m.getEnseignant().cleMin());
                for (int i = 0; i < m.getEnseignant().nbElements(); i++) {
     
                    Element enseignant = new Element("Enseignant");
                    matiere.addContent(enseignant);
                    Attribute idEnseignant = new Attribute("ref", m.getEnseignant().cleCourante());
     
                    enseignant.setAttribute(idEnseignant);
                    m.getEnseignant().positionner(m.getEnseignant().cleSuivante());
                }
     
                tab = m.getNombreHeure();
                Element annee1 = new Element("A1");
                annee1.setText(String.valueOf(tab[0]));
                matiere.addContent(annee1);
     
                Element annee2 = new Element("A2");
                annee2.setText(String.valueOf(tab[1]));
                matiere.addContent(annee2);
     
                Element annee3 = new Element("A3");
                annee3.setText(String.valueOf(tab[2]));
                matiere.addContent(annee3);
     
                Element annee4 = new Element("A4");
                annee4.setText(String.valueOf(tab[3]));
                matiere.addContent(annee4);
     
                Element annee5 = new Element("A5");
                annee5.setText(String.valueOf(tab[4]));
                matiere.addContent(annee5);
            }
            affiche();
            enregistre();
     
        }
     
        public Conteneur importerXML(Conteneur leConteneur, String type) {
     
            Conteneur<String, Enseignant> enseignantConteneur = new Conteneur<String, Enseignant>();
            FileInputStream file;
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            org.w3c.dom.Document doc = null;
     
            try {
                file = new FileInputStream(new File("sauvegarde.xml"));
     
                builder = builderFactory.newDocumentBuilder();
                try {
                    doc = builder.parse(file);
                } catch (IOException ex) {
                    Logger.getLogger(SerialisationXML.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (ParserConfigurationException | SAXException | FileNotFoundException ex) {
                Logger.getLogger(SerialisationXML.class.getName()).log(Level.SEVERE, null, ex);
            }
     
            XPath xpath = XPathFactory.newInstance().newXPath();
     
            if (type.equals("Matieres")) {
     
                NodeList nodeListMatiere = null;
                NodeList sousNodeList = null;
                NodeList nodeListEnseignant = null;
     
                try {
                    nodeListMatiere = (NodeList) xpath.compile("//Matieres/Matiere").evaluate(doc, XPathConstants.NODESET);
                    nodeListEnseignant = (NodeList) xpath.compile("//Enseignants/Enseignant").evaluate(doc, XPathConstants.NODESET);
                } catch (XPathExpressionException ex) {
                    Logger.getLogger(SerialisationXML.class.getName()).log(Level.SEVERE, null, ex);
                }
     
                //On parcourt les Matieres 
                for (int i = 0; i < nodeListMatiere.getLength(); i++) {
                    int tab[] = new int[5];
                    int k = 0;
     
                    try {
                        sousNodeList = (NodeList) xpath.compile("//Matieres/Matiere[@id='"+(i+1)+"']").evaluate(doc, XPathConstants.NODE);
                    } catch (XPathExpressionException ex) {
                        Logger.getLogger(SerialisationXML.class.getName()).log(Level.SEVERE, null, ex);
                    }
     
                    //On parcourt la premiere matiere
                    for (int j = 0; j < sousNodeList.getLength(); j++) {
     
                        //Si un element correspond à A1, A2 .. on recupere son contenu dans tab
                        if (sousNodeList.item(j).getNodeName().equals("A" + (k + 1))) {
                            tab[k] = Integer.valueOf(sousNodeList.item(j).getTextContent());
                            k++;
                        }
                    }
     
                    String numero;
     
                    //On parcourt la premiere matiere
                    for (int j = 0; j < sousNodeList.getLength(); j++) {
                        //Si on trouve un noeud Enseignant on recupere sa reference
                        if (sousNodeList.item(j).getNodeName().equals("Enseignant")) {
                            numero = sousNodeList.item(j).getAttributes().getNamedItem("ref").getTextContent();
                            System.out.println(numero);
                            //Et on cherche cette reference dans les Enseignants
                            for (int l = 0; l < nodeListEnseignant.getLength(); l++) {
                                //Si on la trouve on cree un nouvel enseignant que l'on ajoute a conteneurEnseignant
                                if (nodeListEnseignant.item(l).getAttributes().getNamedItem("id").getTextContent().equals(numero)) {
                                    Enseignant b = new Enseignant(nodeListEnseignant.item(Integer.valueOf(numero)).getChildNodes().item(1).getTextContent(), nodeListEnseignant.item(Integer.valueOf(numero)).getChildNodes().item(2).getTextContent());
                                    enseignantConteneur.ajouter(numero, b);
                                }
                            }
     
                        }
                    }
                    //On construit la matiere à partire des for precedents et on l'ajoute au conteneur à retourner
                    Matieres a = new Matieres(nodeListMatiere.item(i).getFirstChild().getTextContent(), tab, enseignantConteneur);
                    leConteneur.ajouter(nodeListMatiere.item(i).getAttributes().getNamedItem("id").getTextContent(), a);
                }
     
            } else {
                //a venir
            }
            return leConteneur;
        }
     
        public void affiche() {
            try {
                //On utilise ici un affichage classique avec getPrettyFormat()
                XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
                sortie.output(document, System.out);
            } catch (java.io.IOException e) {
            }
        }
     
        public void enregistre() {
            try {
                //On utilise ici un affichage classique avec getPrettyFormat()
                XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
                sortie.output(document, new FileOutputStream("sauvegarde.xml"));
            } catch (java.io.IOException e) {
            }
        }
    }
    Et voici la le fichier xml avec lequel je travaille

    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
    <?xml version="1.0" encoding="UTF-8"?>
    <Sauvegarde>
      <Enseignants>
        <Enseignant id="1">
          <nom>MAH1</nom>
          <prenom>Marc1</prenom>
        </Enseignant>
        <Enseignant id="2">
          <nom>MAH2</nom>
          <prenom>Marc2</prenom>
        </Enseignant>
        <Enseignant id="3">
          <nom>MAH3</nom>
          <prenom>Marc3</prenom>
        </Enseignant>
        <Enseignant id="4">
          <nom>MAH4</nom>
          <prenom>Marc4</prenom>
        </Enseignant>
      </Enseignants>
      <Matieres>
        <Matiere id="1">
          <Titre>Francais</Titre>
          <Enseignant ref="1" />
          <Enseignant ref="2" />
          <Enseignant ref="3" />
          <Enseignant ref="4" />
          <A1>4</A1>
          <A2>1</A2>
          <A3>1</A3>
          <A4>1</A4>
          <A5>1</A5>
        </Matiere>
        <Matiere id="2">
          <Titre>Anglais</Titre>
          <Enseignant ref="1" />
          <Enseignant ref="2" />
          <Enseignant ref="3" />
          <Enseignant ref="4" />
          <A1>4</A1>
          <A2>1</A2>
          <A3>1</A3>
          <A4>1</A4>
          <A5>1</A5>
        </Matiere>
        <Matiere id="3">
          <Titre>Math</Titre>
          <Enseignant ref="1" />
          <Enseignant ref="2" />
          <Enseignant ref="3" />
          <Enseignant ref="4" />
          <A1>4</A1>
          <A2>1</A2>
          <A3>1</A3>
          <A4>1</A4>
          <A5>1</A5>
        </Matiere>
        <Matiere id="4">
          <Titre>Histoire</Titre>
          <Enseignant ref="1" />
          <Enseignant ref="2" />
          <Enseignant ref="3" />
          <Enseignant ref="4" />
          <A1>4</A1>
          <A2>1</A2>
          <A3>1</A3>
          <A4>1</A4>
          <A5>1</A5>
        </Matiere>
      </Matieres>
    </Sauvegarde>
    Merci d'avance ! =)

  2. #2
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    Comment pourrait-on te répondre si on ne connait pas la question ? Expliques au moins ce que tu cherches à obtenir et ce que tu obtiens ! Quel xpath ne te permet pas d'obtenir le résultat escompté ? Est-ce que tu obtiens une exception et laquelle le cas échéant ? On ne va pas analyser ton code et ton fichier pour essayer de deviner qu'est-ce-qui n'est pas conforme à tes espérances.
    L'expression "ça marche pas" ne veut rien dire. Indiquez l'erreur, et/ou les comportements attendus et obtenus, et donnez un Exemple Complet Minimal qui permet de reproduire le problème.
    La plupart des réponses à vos questions sont déjà dans les FAQs ou les Tutoriels, ou peut-être dans une autre discussion : utilisez la recherche interne.
    Des questions sur Java : consultez le Forum Java. Des questions sur l'EDI Eclipse ou la plateforme Eclipse RCP : consultez le Forum Eclipse.
    Une question correctement posée et rédigée et vous aurez plus de chances de réponses adaptées et rapides.
    N'oubliez pas de mettre vos extraits de code entre balises CODE (Voir Mode d'emploi de l'éditeur de messages).
    Nouveau sur le forum ? Consultez Les Règles du Club.

Discussions similaires

  1. Recuperer des données avec return
    Par osmanab dans le forum Débuter avec Java
    Réponses: 6
    Dernier message: 12/05/2010, 08h43
  2. probleme de recuperation des saisie avec gtkentry
    Par lazoir dans le forum GTK+ avec C & C++
    Réponses: 8
    Dernier message: 25/04/2010, 21h40
  3. recupere des properiètes avec selevt HQL
    Par lionel84 dans le forum Hibernate
    Réponses: 4
    Dernier message: 22/08/2008, 14h22
  4. Réponses: 2
    Dernier message: 12/05/2008, 18h17
  5. Envoyer et recuperer des buffers avec les Socket
    Par kaderscream dans le forum C++Builder
    Réponses: 2
    Dernier message: 19/08/2006, 11h44

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