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

JavaScript Discussion :

Récupérer les informations d'un fichier XML


Sujet :

JavaScript

  1. #21
    Membre à l'essai
    Homme Profil pro
    Chef de Projet Informatique (Sécurité & Réseaux)
    Inscrit en
    Juin 2018
    Messages
    26
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de Projet Informatique (Sécurité & Réseaux)
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Juin 2018
    Messages : 26
    Points : 10
    Points
    10
    Par défaut
    Bonjour à tous,

    J'ai trouvé la solution pour générer et récupérer des identifiants uniques.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    var lastId = 1;
     
    function getUniqueId()
    {
    return lastId ++;
    }
    en suite j'appelle ma fonction avec
    De plus j'ai construit mon fichier au format souhaité à l'aide de plusieurs fonctions, tout fonctionne parfaitement (enfin presque )

    Je vous poste le code global et le résultat :
    EDIT: j'ai modifié le code avec plus de commentaires et en séparant les fonctions de manière plus visuelle afin de faciliter la lecture et la compréhension de ce dernier:

    Code html : 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
    <!DOCTYPE html>
    <html lang="fr">
        <body>
            <main>
                <h1> "Script réalisé avec l'aide reçue par les développeurs de developpez.net"</h1>
                <pre id="result"></pre>
            </main>
            <script>
    /* Déclaration des variables */        
                            var TAB = "  ";
                            var CR =  "\n";
                            var LT =  '"'; 
                            
                            var ret = "";
                            var reto = "";
                            var retou = "";
                                    
                var lastId = 1;
                var lastId1 = 1;  
                
                var child, x, y;
                
                var IDs;
                var IDt;
                var test = "";
    /************************************************************************************************************/ 
    /* Récupération et ouverture du document XML */
                "use strict";
                var url = "Bra.xml";       // mettre ici ton url
                var xmlhttp = new XMLHttpRequest();
            
                    xmlhttp.onreadystatechange = function() {
                            if (4 === this.readyState) {  /* DONE */
                                    if (200 === this.status) {  /* LOADING */
                                            fctCallBack(this);
                                    } else {
                                            console.warn("Erreur %d lors du chargement du fichier %s !", this.status, url);
                                    }
                            }
                };
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
    /************************************************************************************************************/
    /* Création de l'entête du document GEXF */
                function createAttr(elem, indent){
                    indent += TAB;
        
                    ret += "<?xml version=" + LT + "1.0" + LT + "encoding=" + LT + "UTF-8" + LT + "?>" + CR;
                    ret += "<gexf xmlns=" + LT + "http://www.gexf.net/1.2draft" + LT + " xmlns:xsi=" + LT + "http://www.w3.org/2001/XMLSchema-instance" + LT + " xsi:schemaLocation=" + LT + "http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" + LT + " version=" + LT + "1.2" + LT + ">" + CR;
                    ret += indent + "<graph defaultedgetype=" + LT + "directed" + LT + ">" + CR + CR;
    /* Création et définition de l'attribue value pour les nodes */
                            ret += indent + "<attributes class=" + LT + "node" + LT + ">" + CR;
                    ret += indent + indent + "<attribute id=" + LT + "0" + LT + "title=" + LT + "Value" + LT + "type=" + LT + "string" + LT + "/>" + CR;
                            ret += indent + indent + "<default>true</default>" + CR;
                            ret += indent + "</attributes>" + CR + CR + CR;
                            ret += indent + "<nodes>" + CR;   
                            
                    return ret;
                }
    /************************************************************************************************************/
    /* Création d'un identifiant unique */
                function getUniqueId() {
                    return lastId1 ++;
                    return lastId ++;
                }     
    /************************************************************************************************************/
    /* Récupération des noeuds parents et enfants avec affichage de leur valeur */
                function getChildren(elem, indent) {
                            var retour = "";
                            var children = elem.childNodes;
                            var nbChildren = children.length;
                            var i;
                            indent += TAB;
                    
                            for (i = 0; i < nbChildren; i += 1) {
                                
                                    child = children[i];
     
                                    // si élément est de type ELEMENT_NODE
                                    if (1 === child.nodeType) {
                                        
                           x = lastId++;
                           
                                        // si des enfants
                                            if (child.childElementCount) {
                           
                            // si le noeud n'a pas d'attribut, retourne l'identifiant et le nom du noeud
                                                    retour += indent + indent + "<node id=" + LT + x + LT + " " + "label=" + LT + child.tagName + LT + ">" + CR;
                                retour += indent + indent + "</node>" + CR;
        
                                            // on y retourne pour la suite (récursivité)
                                            retour += getChildren(child, indent);
                                            } else {
                                            // rédup. attributes si existent pour affichage
                                                    if (child.hasAttributes()) {
                                                            var attrs = child.attributes;
                                                            var item;
                                                            var text = [];
                                                            
                                                            for (item = 0; item < attrs.length; item += 1) {
                                                                    text.push(attrs[item].name + " = " + attrs[item].value);
                                                            }
                                                    child.textContent = text.join(", ");
                                                    }
                                                    
                                                    // si le noeud a un ou plusieurs attributs, retourne l'identifiant, le nom et l'attribut du noeud
                                                    retour += indent + indent + "<node id="  + LT + x + LT + " " + "label="  + LT + child.tagName  + LT + ">" + CR
                                                    retour += indent + indent + indent + "<attvalues>" + CR;
                                                    retour += indent + indent + indent + indent + "<attvalue for="  + LT  +"0"  + LT + " " + "value="  + LT + child.textContent  + LT + "/>" + CR;
                                                    retour += indent + indent + indent + "</attvalues>" + CR;
                                                    retour += indent + indent + "</node>" + CR;
                                            }
                                    }
                                    else { /* on ne fait rien */ }
                            } 
                            // fin balise si existe
                            return retour;
                }
    /************************************************************************************************************/    
    /* Fermeture de la balise "nodes" et ouverture de la balise "edge" */ 
                function edge(elem, indent) {
                            indent += TAB;
                            retou += indent + indent + "</nodes>" + CR + CR + CR;
                    retou += indent + indent + "<edge>" + CR;
                     
                    return retou;
                }
    /************************************************************************************************************/    
    /* Récupération des liens entre les noeuds parents et enfants */
        function getTarget(elem, indent) {
                            var children = elem.childNodes;
                            var nbChildren = children.length;
                            var j;
                            indent += TAB;
                            var retourn = ""
        
                    IDs = "Parent";
                    IDt = "Enfant";
                        
                        
                            for (j = 0; j < nbChildren; j += 1) {
                                
                                    child = children[j];
        
                                    // si élément est de type ELEMENT_NODE
                                    if (1 == child.nodeType) {
                                        
        
                            
         /*                   if (child.parentNodes){
                                IDs = getChildren(elem, indent).x;
                            }
                            else
                            {   
                                IDt = getChildren(elem, indent).x;
                            }
        */
                            y = lastId1 ++;
                                
                                test = TAB + TAB + TAB + "<edge id=" + LT + y + LT + " " + "source=" + LT + IDs + LT + " " + "target=" + LT + IDt + LT + "/>" + CR;                         // si des enfants
                                            
                                            if (child.childElementCount) {
                                      
                                                
                                            // prise en compte du target
              
                                retourn += test; 
        
                                                    // on y retourne pour la suite
                                                        
                                                    retourn += getTarget(child, indent);
                                                    
                                                    
                                            } else {
        
                                                    retourn += test; 
                                            }
                                    }
                                    else { /* on ne fait rien */ }
                            } 
                            return retourn;
                }
    /************************************************************************************************************/    
    /* Fermeture des balises "edges", "graph" et "gexf" */
                function closeFile (elem, indent){
                            indent += TAB;
                    reto += indent + indent + "</edges>" + CR + CR;
                    reto += indent + "</graph>" + CR;
                    reto += "</gexf>" + CR;
                    
                    return reto;
                }
    /************************************************************************************************************/   
    /* Appel des différentes fonctions pour la création du document GEXF */ 
                function fctCallBack(xml) {
                            var xmlDoc = xml.responseXML;
                            var txt = createAttr(xmlDoc, "");
                            var text = getChildren(xmlDoc, "");
                            var txte = edge(xmlDoc, "");
                            var texte = getTarget(xmlDoc, "");
                            var textes = closeFile(xmlDoc, "");
                            document.getElementById("result").textContent = txt + text + txte + texte + textes;
                }
            </script>
        </body>
    </html>

    voici le résultat:
    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
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    "Script réalisé avec l'aide reçue par les développeurs de developpez.net"
    <?xml version="1.0"encoding="UTF-8"?>
    <gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">
      <graph defaultedgetype="directed">
     
      <attributes class="node">
        <attribute id="0"title="Value"type="string"/>
        <default>true</default>
      </attributes>
     
     
      <nodes>
        <node id="1" label="EL">
        </node>
            <node id="2" label="BRANCHES">
            </node>
                <node id="3" label="BRA">
                </node>
                    <node id="4" label="SEGMENT">
                            <attvalues>
                                    <attvalue for="0" value="BNS0088"/>
                            </attvalues>
                    </node>
                    <node id="5" label="SEGMENT">
                            <attvalues>
                                    <attvalue for="0" value="BNS0090"/>
                            </attvalues>
                    </node>
                    <node id="6" label="ENVIRONMENTS">
                    </node>
                        <node id="7" label="ENVIRONMENTTYPE">
                                  <attvalues>
                                            <attvalue for="0" value="PRESSURISED"/>
                                  </attvalues>
                        </node>
        </nodes>
     
     
        <edge>
          <edge id="1" source="Parent" target="Enfant"/>
          <edge id="2" source="Parent" target="Enfant"/>
          <edge id="3" source="Parent" target="Enfant"/>
          <edge id="4" source="Parent" target="Enfant"/>
          <edge id="5" source="Parent" target="Enfant"/>
          <edge id="6" source="Parent" target="Enfant"/>
          <edge id="7" source="Parent" target="Enfant"/>
        </edges>
     
      </graph>
    </gexf>

    Mon dernier problème est la récupération des identifiants parents et enfants (que j'ai nommé "ID s" pour le node parent et "ID t" pour le node enfant).

    Mon objectif est de créer des liens qui partent des nodes parents vers les nodes enfants.

    Cela se passe dans la fonction getTarget que je vous reposte ci-dessous
    Code html : 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
    <!DOCTYPE html>
    <html lang="fr">
        <body>
            <main>
              <pre id="result"></pre>
            </main>
            <script>
            "use strict";
            var url = "Bra.xml";       // mettre ici ton url
            var xmlhttp = new XMLHttpRequest();
            
                    xmlhttp.onreadystatechange = function() {
                            if (4 === this.readyState) {  /* DONE */
                                    if (200 === this.status) {  /* LOADING */
                                            fctCallBack(this);
                                    } else {
                                            console.warn("Erreur %d lors du chargement du fichier %s !", this.status, url);
                                    }
                            }
            };
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
     
     
            var lastId1 = 1;
            function getUniqueId() {
                return lastId1 ++;
            }          
            
            
            function getTarget(elem, indent) {
     
                            var TAB = "  ";
                            var CR =  "\n";
                            var LT =  '"';
                
                            var retourn = "";
                            var children = elem.childNodes;
                            var nbChildren = children.length;
                            var child;
                            var i;
                            indent += TAB;
                        
                        var IDs = "ID s";                   // ID Source
                        var IDt = "ID t"                    // ID Target
                        var test = "";
                        
                        var y;
     
                            for (i = 0; i < nbChildren; i += 1) {
                                
                                    child = children[i];
     
                                    // si élément est de type ELEMENT_NODE
                                    if (1 == child.nodeType) {
                            y = lastId1 ++;
                        test = TAB + TAB + TAB + "<edge id=" + LT + y + LT + " " + "source=" + LT + IDs + LT + " " + "target=" + LT + IDt + LT + "/>" + CR;                         // si des enfants
                                            if (child.childElementCount) {
     
                                            // prise en compte du target Parent-enfant
              
                            retourn += test; 
     
                                            // on y retourne pour la suite
                                                
                                            retourn += getTarget(child, indent);
                                            
                                            
                                            } else {
     
                                                    retourn += test; 
                                            }
                                    }
                                    else { /* on ne fait rien */ }
                            } 
                            return retourn;
            }
            
            function fctCallBack(xml) {
                            var xmlDoc = xml.responseXML;
                            var texte = getTarget(xmlDoc, "");
                            document.getElementById("result").textContent = texte;
            }
            </script>
        </body>
    </html>

    et son résultat associé

    Code xml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
          <edge id="1" source="ID s" target="ID t"/>
          <edge id="2" source="ID s" target="ID t"/>
          <edge id="3" source="ID s" target="ID t"/>
          <edge id="4" source="ID s" target="ID t"/>
          <edge id="5" source="ID s" target="ID t"/>
          <edge id="6" source="ID s" target="ID t"/>
          <edge id="7" source="ID s" target="ID t"/>

    Si quelqu'un a une idée je suis preneur, dans le cas contraire je reviendrai vers vous quand j'aurai trouvé une solution.
    Cordialement,
    Pal31

  2. #22
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 075
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 075
    Points : 44 657
    Points
    44 657
    Par défaut
    Si quelqu'un a une idée je suis preneur ...
    il serait peut être bon que tu indiques la relation qu'il y a en un élément <edge> et un élément <node> et notamment à quoi correspondent les attributs, de<edge>, source et target dans les <node>.

    Je dois admettre que j'ai décroché en lisant GEXF File Format

  3. #23
    Membre à l'essai
    Homme Profil pro
    Chef de Projet Informatique (Sécurité & Réseaux)
    Inscrit en
    Juin 2018
    Messages
    26
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de Projet Informatique (Sécurité & Réseaux)
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Juin 2018
    Messages : 26
    Points : 10
    Points
    10
    Par défaut
    il serait peut être bon que tu indiques la relation qu'il y a en un élément <edge> et un élément <node> et notamment à quoi correspondent les attributs, de<edge>, source et target dans les <node>.
    Oui, et je m'excuse de ne pas l'avoir fait.
    Mon objectif est de créer les liens entre les noeuds parents et enfants ce qui permettrait de suivre un chemin et d'avoir une vue globale du document sous forme graphique.

    L'élément <edge> est le chemin entre l'élément <source> (noeud parent) et l'élément <target> (noeud enfant).

    dans mon cas:
    Nom : Objectif.png
Affichages : 105
Taille : 88,6 Ko

    Ai-je pu te donner assez d'informations? Si besoin n'hésite pas à me redemander des détails.
    Encore merci pour ton aide.

  4. #24
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 075
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 075
    Points : 44 657
    Points
    44 657
    Par défaut
    Ce que je te propose c'est la mise à jour d'un « tableau de relation » lors de l'analyse des noeuds.

    Cela pourrait être fait de la façon suivante suivant la structure ci-dessous
    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
    /**
     * Gestion des relations pour <edges>
     */
    var IDRelation = {
      indice: 0,
      edge: [],
      getID: function(idxParent, elem) {
        var previousId = this.indice;             // id précédente
        this.indice += 1;
        // stoquage donnée
        this.edge.push({
           "id": previousId
          ,"source": idxParent
          ,"target": this.indice
          ,"sourceTag": elem.parentNode.tagName   // pour vérif
          ,"targetTag": elem.tagName              // pour vérif
        });
        return (this.indice);
      }
    };
    dans la fonction de récupérations de noeuds il suffit d’appeler la méthode getID de la façon suivante
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    // récup. ID et mise à jour table liaison
    id = IDRelation.getID(indiceParent, child)
    Concernant l'intégration dans ton code source, j'ai eu plus vite fait de reprendre le code que je t'ai fourni initialement en prenant en compte tes évolutions.

    Cela donne
    Code html : 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
    <!DOCTYPE html>
    <html lang="fr">
    <head>
    <meta charset="UTF-8">
    <title>Lecture arborescence fichier XML</title>
    <meta name="Author" content="NoSmoking">
    <meta name="DVP-discussion" content="d1946638">
    <meta name="DVP-version" content="2.0">
    <style>
    html, body {
      margin: 0;
      padding: 0;
      font: 1em/1.25 Verdana,sans-serif;
    }
    main {
      display: block;
      margin: 0 auto;
      padding: 0;
      max-width: 60em;
    }
    h1, h2, h3 {
      margin: .5em 0;
      color: #069;
    }
    pre {
      margin: 0 0 .5em;
      border: 1px solid #CCC;
      text-shadow: 1px 1px 0 #FFF;
      background: #EEE;
      white-space: pre-wrap;
    }
    </style>
    </head>
    <body>
    <main>
      <header>
        <h1>Résultat récursif</h1>
      </header>
      <section>
        <h2>Résultat</h2>
        <pre id="result"></pre>
      </section>
      <section>
        <h2>Ressources</h2>
        <p><a href="https://gephi.org/gexf/format/index.html">https://gephi.org/gexf/format/index.html</a></p>
      </section>
    </main>
    <script>
    "use strict";
    /* si utilisé avec innerHTML
    var TAB = "&nbsp;&nbsp;";
    var CR =  "<br>";
    var LT =  "&lt;";
    */
    /* si utilisé avec textContent */
    var TAB = "    ";
    var CR =  "\n";
     
    /**
     * Gestion des relations pour <edges>
     */
    var IDRelation = {
      indice: 0,
      edge: [],
      getID: function(idxParent, elem) {
        var previousId = this.indice;             // id précédente
        this.indice += 1;
        // stoquage donnée
        this.edge.push({
           "id": previousId
          ,"source": idxParent
          ,"target": this.indice
          ,"sourceTag": elem.parentNode.tagName   // pour vérif
          ,"targetTag": elem.tagName              // pour vérif
        });
        return (this.indice);
      }
    };
    /**
     * version 2.0
     */
    function getNodes(elem, indent, indiceParent) {
      var retour = "";
      var children = elem.childNodes;
      var nbChildren = children.length;
      var child;
      var id;
      var i;
     
      for (i = 0; i < nbChildren; i += 1) {
        child = children[i];
        // si élément est de type ELEMENT_NODE
        if (1 === child.nodeType) {
          // récup. ID et mise à jour table liaison
          id = IDRelation.getID(indiceParent, child);
          // si des enfants
          if (child.childElementCount) {
            // prise en compte du tagName
            retour += indent + TAB + '<node id="' + id + '" label="' + child.tagName + '">' + CR;
            retour += indent + TAB + '</node>' + CR;
            // on y retourne pour la suite
            retour += getNodes(child, indent, id /* indiceParent */ );
          }
          else {
            // récup. attributes si existent pour affichage
            if (child.hasAttributes()) {
              var attrs = child.attributes;
              var item;
              var text = [];
              for (item = 0; item < attrs.length; item += 1) {
                text.push(attrs[item].name + " = " + attrs[item].value);
              }
              child.textContent = text.join(", ");
            }
            retour += indent + TAB + '<node id="' + id + '" label="' + child.tagName + '">' + CR;
            retour += indent + TAB + TAB + "<attvalues>" + CR;
            retour += indent + TAB + TAB + TAB + '<attvalue for="0" value="' + child.textContent + '"/>' + CR;
            retour += indent + TAB + TAB + '</attvalues>' + CR;
            retour += indent + TAB + '</node>' + CR;
          }
        }
        else {
          /* on ne fait rien */
        }
      }
      // fin balise si existe
      //var endTag = elem.tagName ? (indent.substring(TAB.length) + LT +"/" + elem.tagName + ">" + CR) : "";
      return retour;
    }
     
    /* Création de l'entête du document GEXF */
    function getEntete(indent) {
      indent = indent || '';
      var text = [];
      text.push('<?xml version="1.0" encoding="UTF-8"?>');
      text.push('<gexf xmlns="http://www.gexf.net/1.2draft" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd" version="1.2">');
      text.push(indent + TAB + '<graph defaultedgetype="directed">');
      text.push(indent + TAB + TAB + '<attributes class="node">');
      text.push(indent + TAB + TAB + TAB + '<attribute id="0" title="Value" type="string"/>');
      text.push(indent + TAB + TAB + TAB + '<default>true</default>');
      text.push(indent + TAB + TAB + '</attributes>');
      return text.join(CR);
    }
    function getEdges(indent) {
      indent = indent || '';
      var data = IDRelation.edge;
      var text = [indent + '<edges>'];
      data.shift();                         // supprime le premier non concerné
      data.forEach(function(obj, ind) {
        text.push(indent + TAB + '<edge id="' + obj.id + '" source="' + obj.source + '" target="' + obj.target + '"/>');
        //text.push(indent + TAB + '<edge id="' + obj.id + '" source="' + obj.sourceTag + '" target="' + obj.targetTag + '"/>');
      });
      text.push(indent + '</edges>');
      return text.join(CR);
    }
    /* Fermeture des balises <graph> et <gexf> */
    function getEmpied(indent) {
      indent = indent || '';
      var text = [];
      text.push(indent + TAB + '</graph>');
      text.push(indent + '</gexf>');
      return text.join(CR);
    }
    /**
     *
     */
    function fctCallBack(xml) {
      var xmlDoc = xml.responseXML;
      var indent = TAB + TAB;
      var text = [];;
      text.push(getEntete());
      text.push(indent + "<nodes>" + CR + getNodes(xmlDoc, indent) + indent + "</nodes>");
      text.push(getEdges(indent));
      text.push(getEmpied());
      document.getElementById("result").textContent = text.join(CR);
    }
     
    /**
     * c'est parti ...
     */
    var url = "data-XML.xml";       // mettre ici ton url
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (4 === this.readyState) {  /* DONE */
        if (200 === this.status) {  /* LOADING */
          fctCallBack(this);
        }
        else {
          console.warn("Erreur %d lors du chargement du fichier %s !", this.status, url);
        }
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    </script>
    </body>
    </html>
    J'ai modifié certaines approches, mais rien d'essentiel, et n'ayant pas les moyens de tester en « vraie grandeur » il doit y avoir des ajustements à faire.

  5. #25
    Membre à l'essai
    Homme Profil pro
    Chef de Projet Informatique (Sécurité & Réseaux)
    Inscrit en
    Juin 2018
    Messages
    26
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de Projet Informatique (Sécurité & Réseaux)
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Juin 2018
    Messages : 26
    Points : 10
    Points
    10
    Par défaut
    Bonjour, merci pour ta réponse, c'est exactement ce qu'il me fallait, après plusieurs tests sur quelques documents XML, je n'ai à priori pas vu d'ajustement à faire.
    Maintenant il ne me reste plus qu'une dernière chose à faire, c'est pouvoir sélectionner mon fichier XML, lancer la transformation et l'enregistrer au format GEXF.

    Pour cela en cherchant j'ai trouvé une fonction réalisée par Watilin sur cette discussion:
    je vous poste sa fonction

    Code HTML : 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
    <!DOCTYPE html>
    <html lang="fr">
    <head>
      <meta charset="utf-8" />
      <title>Ouvrir, modifier, enregistrer un fichier</title>
      <style>
     
      textarea {
        display: block;
        border: solid thin #6cf;
        padding: 1px;
        width: 100%;
        max-height: 24em;
        overflow: auto;
      }
     
      </style>
    </head>
    <body>
     
    <input type="file" />
     
    <script> "use strict";
     
    const regex = /<content>\s*{Nom_produit}\s*<\/content>/g;
     
    function highlightText($textarea) {
      $textarea.focus();
      let match = regex.exec($textarea.value);
      if (match) {
        let j = regex.lastIndex;
        let i = j - match[0].length;
        $textarea.setSelectionRange(i, j);
        regex.lastIndex = 0;
      }
    }
     
    document.querySelector("input[type=file]")
      .addEventListener("change", (event) => {
        let file = event.target.files[0];
        if (!file) {
          console.log("Aucun fichier sélectionné");
          return;
        }
        else {
          console.log(file);
          let reader = new FileReader();
     
          reader.onload = () => {
            let $ta = document.querySelector("textarea");
            let $button = document.querySelector("button");
            if (!$ta) {
              $ta = document.createElement("textarea");
              $ta.cols = 80;
              $ta.rows = 15;
              $button = document.createElement("button");
              $button.textContent = "Enregistrer";
     
              document.body.append($ta, $button);
     
              $button.onclick = () => {
                let blob = new Blob([ $ta.value ], { type: "text/xml" });
                let blobUrl = URL.createObjectURL(blob);
     
                let $a = document.createElement("a");
                $a.download = file.name;
                $a.href = blobUrl;
     
                document.body.append($a);
                $a.click();
                $a.remove();
                URL.revokeObjectURL(blobUrl);
              };
            }
     
            $ta.value = reader.result;
            highlightText($ta);
          };
     
          reader.readAsText(file);
        }
      });
     
    </script>
    </body>
    </html>
    Je vais l'étudier pour voir si je peux l'adapter à mon besoin car c'est exactement le principe que je recherche d'ouverture de document, et d'enregistrement.
    Je pense qu'il faudrait modifier le principe d'édition du document pour qu'il soit fait automatiquement par les fonctions appelées par le script, et le principe d'enregistrement, qu'il ne soit pas au format XML mais au format GEXF.

    Merci.

  6. #26
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    17 075
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 17 075
    Points : 44 657
    Points
    44 657
    Par défaut
    Maintenant il ne me reste plus qu'une dernière chose à faire ...
    la problématique devient autre et ne concerne plus la récupération/transformation de tes données XML

    Pour rappel :
    une question = une discussion

    Poser plusieurs questions dans un seul et même fil nuit grandement à la qualité du forum : notamment, lors d'une recherche, tout le contenu du fil n'est pas indiqué dans le titre, elle devient donc plus ardue.

  7. #27
    Membre à l'essai
    Homme Profil pro
    Chef de Projet Informatique (Sécurité & Réseaux)
    Inscrit en
    Juin 2018
    Messages
    26
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de Projet Informatique (Sécurité & Réseaux)
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Juin 2018
    Messages : 26
    Points : 10
    Points
    10
    Par défaut
    Oui pas de problème désolé, je recréer une nouvelle discussion avec le dernier message, je place celle-ci en résolu.
    Encore merci

+ Répondre à la discussion
Cette discussion est résolue.
Page 2 sur 2 PremièrePremière 12

Discussions similaires

  1. Réponses: 8
    Dernier message: 09/02/2008, 17h21
  2. [XSLT] Problème de génération de code javascript (inclure) via XSLT
    Par fragmonster dans le forum XSL/XSLT/XPATH
    Réponses: 3
    Dernier message: 23/04/2007, 14h49
  3. Réponses: 16
    Dernier message: 18/10/2006, 22h52
  4. Problème de paramètres dans mon code javascript
    Par cocacollection dans le forum Général JavaScript
    Réponses: 7
    Dernier message: 15/03/2006, 10h53
  5. problème de code javascript pour une vue 360°
    Par tomguiss dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 14/03/2006, 22h50

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