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

C# Discussion :

Lire et écrire dans un fichier xml [Débutant]


Sujet :

C#

  1. #21
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    Pour l'ouvrir avec visual studio fait:
    Fichier->Ouvrir le site Web->(onglet systeme de fichier)sélectionne le répertoire ou se trouve ton application
    tu devrais le voir apparaitre à gauche dans l'explorateur de solution

    pour les balises essaye de les fermer toutes en faisant autant de endElement qu'il y a de startElement
    si ça marche toujour pas je testerais moi même

  2. #22
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    Bon j'avance un peu mais c'est pas encore ça...

    Voilà le résultat obtenu:

    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
    <?xml version="1.0" encoding="utf-8"?>
    <groupe>
      <agence nom="agence1">
        <utilisateur>
          <prenom>sheira</prenom>
          <fond>fond1.jpg</fond>
        </utilisateur>
      </agence>
    </groupe><?xml version="1.0" encoding="utf-8"?>
    <groupe>
      <agence nom="agence1">
        <utilisateur>
          <prenom>sheira</prenom>
          <fond>fond1.jpg</fond>
        </utilisateur>
      </agence>
      <agence nom="agence1">
        <utilisateur>
          <prenom>Lila</prenom>
          <fond>fond2.jpg</fond>
        </utilisateur>
      </agence>
    </groupe>
    Il me recrée le document à la suite...

    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
     
    XmlDocument doc = new XmlDocument();
    doc.Load(f);
    XmlNode racine = doc.DocumentElement;
     
    XmlElement ag = doc.CreateElement("agence");
    XmlAttribute attr = doc.CreateAttribute("nom");
    attr.Value = r[0];
    ag.SetAttributeNode(attr);
     
    XmlElement user = doc.CreateElement("utilisateur");
    XmlElement firstname = doc.CreateElement("prenom");
    firstname.InnerText = "Lila";
    XmlElement bg = doc.CreateElement("fond");
    bg.InnerText = "fond2.jpg";
     
    ag.AppendChild(user);
    user.AppendChild(firstname);
    user.AppendChild(bg);
    racine.InsertAfter(ag, racine.FirstChild);
    doc.Save(f);
    J'y suis presque mais là je ne vois plus ou chercher, un peu d'aide serai la bienvenue. Merci

  3. #23
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    et c'est quoi le résultat que tu veux obtenir?

  4. #24
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    Au début j'ai ce document XML:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <?xml version="1.0" encoding="utf-8"?>
    <groupe>
      <agence nom="agence1">
        <utilisateur>
          <prenom>sheira</prenom>
          <fond>fond1.jpg</fond>
        </utilisateur>
      </agence>
    </groupe>
    Quand je rajoute un noeud agence je veux obtenir:

    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" encoding="utf-8"?>
    <groupe>
      <agence nom="agence1">
        <utilisateur>
          <prenom>sheira</prenom>
          <fond>fond1.jpg</fond>
        </utilisateur>
      </agence>
      <agence nom="agence2">
        <utilisateur>
          <prenom>Lila</prenom>
          <fond>fond2.jpg</fond>
        </utilisateur>
      </agence>
    </groupe>

  5. #25
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    Bon ben j'ai continuer à avancer....


    J'arrive à rajouter des noeuds ou je veux.... le soucis c'est qu'il m'en rajoute tout le temps parce que je passe jamais au noeud suivant, j'ai pourtant une boucle fort mais rien n'y fait... je veux d'abord qui 'il vérifie que l'enregistrement n'existe dans aucun des noeuds avant de me le rajouter mais c'est pas le cas il s'arrête au premier noeud... merci d'avance pour votre aide.

    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
    	try
     
    	{
    		String[] theArray = new string[] {"utilisateur", "prenom", "fond"};
    		String[] r = { "agence1", "sheira", "fond1.jpg" };
     
    		String filename = "test2.xml";
    		FileStream f = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.OpenOrCreate, FileAccess.ReadWrite);
     
    		if (f.Length != 0)
    		{
    			XmlDocument doc = new XmlDocument();
    			doc.Load(f);
    			XmlNode racine = doc.DocumentElement;
     
    			if (racine.NodeType == XmlNodeType.Element && racine.Name == "groupe")
    			{
     
    				// Get a list of elements whose names are Agence
    				XmlNodeList nodAgences = doc.GetElementsByTagName("agence");
    				// Since we will look for a specific agence, get the list of all prenom
    				XmlNodeList nodUsers = doc.GetElementsByTagName("utilisateur");
     
    				// Visit each agences
    				for(int i = 0; i < nodAgences.Count; i++)
    				{
     
    					if (((XmlElement)(nodAgences[i])).HasAttribute("nom")){
    						string nomAgence = ((XmlElement)(nodAgences[i])).GetAttribute("nom");
    						Response.Write(r[0] );
    							if (nomAgence == r[0]){
    								Response.Write("ok:agence ");							
    								//for(int j = 0; j < nodUsers.Count; j++){
    									String prenom = nodUsers[i].InnerText;
    									Response.Write(prenom);
    									if(prenom == "she")
    									{
    										Response.Write("ok:utilisateur ");
    										// l'utilisateur existe déjà 
    										string nomFond = ((XmlElement)(nodUsers[i])).GetAttribute("fond");
    										Response.Write(nomFond);
     
    										if (nomFond != "fond2.jpg"){
    											Response.Write("ok:changeFond ");
    											// On modifie le fond => je remplace le noeud complet
    											XmlElement user = doc.CreateElement("utilisateur");
    											user.InnerText = "Lina";
    											XmlAttribute attrFond = doc.CreateAttribute("fond");
    											attrFond.Value = "fond2.jpg";
    											user.SetAttributeNode(attrFond);
    											nodUsers.Item(i).ParentNode.ReplaceChild(user, nodUsers.Item(i));
    										}
    									}
    									else {
    										Response.Write("ok:changeUser ");
    										// je rajoute le noeud complet
    										XmlElement user = doc.CreateElement("utilisateur");
    										user.InnerText = "Lila";
    										XmlAttribute attrFond = doc.CreateAttribute("fond");
    										attrFond.Value = r[2];
    										user.SetAttributeNode(attrFond);
    										nodAgences.Item(i).AppendChild(user);
     
    									}
    								//}
    							}
    							else{
    								XmlElement ag = doc.CreateElement("agence");
    								XmlAttribute attrNom = doc.CreateAttribute("nom");
    								attrNom.Value = r[0];
    								ag.SetAttributeNode(attrNom);
     
    								XmlElement user = doc.CreateElement("utilisateur");
    								user.InnerText = "Lila";
    								XmlAttribute attrFond = doc.CreateAttribute("fond");
    								attrFond.Value = r[2];
    								user.SetAttributeNode(attrFond);
     
    								ag.AppendChild(user);
    								racine.InsertAfter(ag, racine.FirstChild);							
    							}							
    					}					
    				}
     
    				f.Close();
    				doc.Save(HttpContext.Current.Server.MapPath(filename));
    			}
    			f.Close();
    		}
    		else
    		{
     
    			XmlTextWriter xmlw = new XmlTextWriter(f, System.Text.Encoding.UTF8);
     
    			xmlw.Formatting = Formatting.Indented;
     
    			xmlw.WriteStartDocument();
    			xmlw.WriteStartElement("groupe");
    			xmlw.WriteStartElement("agence");
    			xmlw.WriteAttributeString("nom", r[0]);
     
    			xmlw.WriteStartElement("utilisateur");
    			xmlw.WriteAttributeString("fond", r[2]);
    			xmlw.WriteString(r[1]);
     
    			xmlw.WriteEndElement();
    			xmlw.WriteEndElement();
    			xmlw.WriteEndElement();
     
    			xmlw.WriteEndDocument();
     
    			xmlw.Flush();
    			//vide le buffer
     
    			xmlw.Close();
    			// Close the writer
     
    			f.Close();
    		}
     
     
    	}
     
     
     
    	finally {
     
     
    	 }

  6. #26
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    j'ai réussi à faire ça mais je ne comprend pas pourquoi il me rajoute a nouveau une balise 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
    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
     
    try
            {
                String[] r = { "agence1", "sheira", "fond1.jpg" };
     
     
                String filename = "test.xml";
     
                using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    if (f.Length != 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(f);
                        XmlElement racine = doc.DocumentElement;
                        //  on vérifie d'abord que la balise groupe existe 
                        if (racine != null && racine.Name == "groupe")
                        {
                            XmlNodeList noeudsAgence = racine.ChildNodes;
                            if (noeudsAgence.Count > 0)
                            {
                                // on vérifie que le noeud n'existe pas avant de le créer
                                bool exist = false;
                                foreach (XmlNode noeudAgence in noeudsAgence)
                                {
                                    if (noeudAgence.Attributes["nom"].InnerText == r[0] && noeudAgence.FirstChild.InnerText == r[1] && noeudAgence.FirstChild.Attributes["fond"].InnerText == r[2])
                                    {
                                        exist = true;
                                        break;
                                    }
     
                                }
                                // on créer le noeud s'il n'existe pas
                                if (!exist)
                                {
                                    creerNoeud(doc, racine, r);
                                    doc.Save(f);
                                }
                            }
                        }
     
                    }
                    else
                    {
                        XmlDocument doc = new XmlDocument();
                        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "Utf-8",null);
                        doc.AppendChild(declaration);
                        XmlElement racine = doc.CreateElement("groupe");
                        creerNoeud(doc, racine, r);
                        doc.AppendChild(racine);
                        doc.Save(f);
                    }
     
     
                }
            }
            catch (Exception ex)
            {
                //Todo:gestion des exceptions
            }
    et le code de création de noeud
    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
     
    private void creerNoeud(XmlDocument doc, XmlElement racine, string[] donnees)
        {
            XmlElement ag = doc.CreateElement("agence");
            XmlAttribute attrNom = doc.CreateAttribute("nom");
            attrNom.Value = donnees[0];
            ag.SetAttributeNode(attrNom);
            XmlElement user = doc.CreateElement("utilisateur");
            user.InnerText = donnees[1];
            XmlAttribute attrFond = doc.CreateAttribute("fond");
            attrFond.Value = donnees[2];
            user.SetAttributeNode(attrFond);
            ag.AppendChild(user);
            racine.AppendChild(ag);
        }
    faudra quand même ajouter la gestions des erreurs ou faire plus de vérification

  7. #27
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    essaie de mettre
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    doc.Save(HttpContext.Current.Server.MapPath(filename));
    au lieu de

  8. #28
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    J'ai essayé le code comme ça mais j'ai une erreur à la fin du catch :
    } attendue

    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
    <% @Page Language="C#" Debug="true" %>
    <% @Import Namespace="System" %>
    <% @Import Namespace="System.Xml" %>
    <% @Import Namespace="System.IO" %>
    <% @Import Namespace="System.Xml.XPath" %>
     
    <%
     
    try
            {
                String[] r = { "agence1", "sheira", "fond1.jpg" };
     
     
                String filename = "test.xml";
     
                using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    if (f.Length != 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(f);
                        XmlElement racine = doc.DocumentElement;
                        //  on vérifie d'abord que la balise groupe existe 
                        if (racine != null && racine.Name == "groupe")
                        {
                            XmlNodeList noeudsAgence = racine.ChildNodes;
                            if (noeudsAgence.Count > 0)
                            {
                                // on vérifie que le noeud n'existe pas avant de le créer
                                bool exist = false;
                                foreach (XmlNode noeudAgence in noeudsAgence)
                                {
                                    if (noeudAgence.Attributes["nom"].InnerText == r[0] && noeudAgence.FirstChild.InnerText == r[1] && noeudAgence.FirstChild.Attributes["fond"].InnerText == r[2])
                                    {
                                        exist = true;
                                        break;
                                    }
     
                                }
                                // on créer le noeud s'il n'existe pas
                                if (!exist)
                                {
                                    creerNoeud(doc, racine, r);
                                    doc.Save(f);
                                }
                            }
                        }
     
                    }
                    else
                    {
                        XmlDocument doc = new XmlDocument();
                        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "Utf-8",null);
                        doc.AppendChild(declaration);
                        XmlElement racine = doc.CreateElement("groupe");
                        creerNoeud(doc, racine, r);
                        doc.AppendChild(racine);
                        doc.Save(f);
                    }
     
     
                }
            }
            catch (Exception ex)
            {
                //Todo:gestion des exceptions
            }
     
     
    private void creerNoeud(XmlDocument doc, XmlElement racine, string[] donnees)
        {
            XmlElement ag = doc.CreateElement("agence");
            XmlAttribute attrNom = doc.CreateAttribute("nom");
            attrNom.Value = donnees[0];
            ag.SetAttributeNode(attrNom);
            XmlElement user = doc.CreateElement("utilisateur");
            user.InnerText = donnees[1];
            XmlAttribute attrFond = doc.CreateAttribute("fond");
            attrFond.Value = donnees[2];
            user.SetAttributeNode(attrFond);
            ag.AppendChild(user);
            racine.AppendChild(ag);
        }
     
    %>

  9. #29
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    effectivement si on fait ça on a bien une seul balise xml:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    // on créer le noeud s'il n'existe pas
                                if (!exist)
                                {
                                    creerNoeud(doc, racine, r);
                                    f.Close();
                                    doc.Save(HttpContext.Current.Server.MapPath(filename));
                                }
    c'est bien ce que tu cherchais à faire alors ?

  10. #30
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    mais tu mets directement le code comme ça et ça marche ou faut-il que tu le mette dans une fonction ?

  11. #31
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    J'arrive pas à le tester, regardez le message précédent svp j'ai un soucis.
    Merci

  12. #32
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    bein en un seul bloc alors:

    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
     
    try
            {
                String[] r = { "agence2", "sheira", "fond1.jpg" };
     
     
                String filename = "test.xml";
     
                using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    if (f.Length != 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(f);
                        XmlElement racine = doc.DocumentElement;
                        //  on vérifie d'abord que la balise groupe existe 
                        if (racine != null && racine.Name == "groupe")
                        {
                            XmlNodeList noeudsAgence = racine.ChildNodes;
                            if (noeudsAgence.Count > 0)
                            {
                                // on vérifie que le noeud n'existe pas avant de le créer
                                bool exist = false;
                                foreach (XmlNode noeudAgence in noeudsAgence)
                                {
                                    if (noeudAgence.Attributes["nom"].InnerText == r[0] && noeudAgence.FirstChild.InnerText == r[1] && noeudAgence.FirstChild.Attributes["fond"].InnerText == r[2])
                                    {
                                        exist = true;
                                        break;
                                    }
     
                                }
                                // on créer le noeud s'il n'existe pas
                                if (!exist)
                                {
                                    XmlElement ag = doc.CreateElement("agence");
                                    XmlAttribute attrNom = doc.CreateAttribute("nom");
                                    attrNom.Value = r[0];
                                    ag.SetAttributeNode(attrNom);
                                    XmlElement user = doc.CreateElement("utilisateur");
                                    user.InnerText = r[1];
                                    XmlAttribute attrFond = doc.CreateAttribute("fond");
                                    attrFond.Value = r[2];
                                    user.SetAttributeNode(attrFond);
                                    ag.AppendChild(user);
                                    racine.AppendChild(ag);
                                    f.Close();
                                    doc.Save(HttpContext.Current.Server.MapPath(filename));
                                }
                            }
                        }
     
                    }
                    else
                    {
                        XmlDocument doc = new XmlDocument();
                        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "Utf-8",null);
                        doc.AppendChild(declaration);
                        XmlElement racine = doc.CreateElement("groupe");
                        XmlElement ag = doc.CreateElement("agence");
                        XmlAttribute attrNom = doc.CreateAttribute("nom");
                        attrNom.Value = r[0];
                        ag.SetAttributeNode(attrNom);
                        XmlElement user = doc.CreateElement("utilisateur");
                        user.InnerText = r[1];
                        XmlAttribute attrFond = doc.CreateAttribute("fond");
                        attrFond.Value = r[2];
                        user.SetAttributeNode(attrFond);
                        ag.AppendChild(user);
                        racine.AppendChild(ag);
                        doc.AppendChild(racine);
                        doc.Save(f);
                    }
     
     
                }
            }
            catch (Exception ex)
            {
                //Todo:gestion des exceptions
            }

  13. #33
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    oui ca passe merci, par contre tu rajoute tout le noeud à chaque fois , alors que
    si l'agence est bonne
    si je trouve l'utilisateur, je remplace le noeud avec mes infos
    si je trouve pas l'utilisateur, j'ajoute un noeud "utilisateur"
    sinon
    je rajoute l'agence (ce que tu fais déjà)

    Comment faire avec ton booleen exist?

    Et tu ne vérifie que le premier noeud "utilisateur" du noeud "agence" alors que je peux en avoir plein. Je voulais regrouper les utilisateur par agence.
    Mais si je trouve pas de moyen de le faire je vais faire comme ça... le temps joue contre moi... à moins que vous ayez une solution?

    Encore merci pour votre aide

  14. #34
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    je suis d'accord pour avoir une partie de ton salaire
    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
     
    try
            {
                String[] r = { "agence3", "sheira", "fond2.jpg" };
     
     
                String filename = "test.xml";
     
                using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    if (f.Length != 0)
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.Load(f);
                        XmlElement racine = doc.DocumentElement;
                        //  on vérifie d'abord que la balise groupe existe 
                        if (racine != null && racine.Name == "groupe")
                        {
                            XmlNodeList noeudsAgence = racine.ChildNodes;
                            if (noeudsAgence.Count > 0)
                            {
                                // on vérifie que le noeud n'existe pas avant de le créer
                                bool agenceExist = false;
                                bool utilisateurExist = false;
                                foreach (XmlNode noeudAgence in noeudsAgence)
                                {
                                    if (noeudAgence.Attributes["nom"].InnerText == r[0])
                                    {
                                        agenceExist = true;
                                        foreach (XmlNode utilisateur in noeudAgence.ChildNodes)
                                        {
                                            if (utilisateur.InnerText == r[1])
                                            {
                                                utilisateurExist = true;
                                                noeudAgence.FirstChild.Attributes["fond"].Value = r[2];
                                                break;
                                            }
                                        }
                                        if (!utilisateurExist)
                                        {
                                            XmlElement user = doc.CreateElement("utilisateur");
                                            user.InnerText = r[1];
                                            XmlAttribute attrFond = doc.CreateAttribute("fond");
                                            attrFond.Value = r[2];
                                            user.SetAttributeNode(attrFond);
                                            noeudAgence.AppendChild(user);
                                        }
                                    }
     
                                }
     
                                if (!agenceExist)
                                {
                                    XmlElement ag = doc.CreateElement("agence");
                                    XmlAttribute attrNom = doc.CreateAttribute("nom");
                                    attrNom.Value = r[0];
                                    ag.SetAttributeNode(attrNom);
                                    XmlElement user = doc.CreateElement("utilisateur");
                                    user.InnerText = r[1];
                                    XmlAttribute attrFond = doc.CreateAttribute("fond");
                                    attrFond.Value = r[2];
                                    user.SetAttributeNode(attrFond);
                                    ag.AppendChild(user);
                                    racine.AppendChild(ag);
                                }
                                f.Close();
                                doc.Save(HttpContext.Current.Server.MapPath(filename));
     
                            }
                        }
     
                    }
                    else
                    {
                        XmlDocument doc = new XmlDocument();
                        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "Utf-8", null);
                        doc.AppendChild(declaration);
                        XmlElement racine = doc.CreateElement("groupe");
                        XmlElement ag = doc.CreateElement("agence");
                        XmlAttribute attrNom = doc.CreateAttribute("nom");
                        attrNom.Value = r[0];
                        ag.SetAttributeNode(attrNom);
                        XmlElement user = doc.CreateElement("utilisateur");
                        user.InnerText = r[1];
                        XmlAttribute attrFond = doc.CreateAttribute("fond");
                        attrFond.Value = r[2];
                        user.SetAttributeNode(attrFond);
                        ag.AppendChild(user);
                        racine.AppendChild(ag);
                        doc.AppendChild(racine);
                        doc.Save(f);
                    }
     
     
                }
            }
            catch (Exception ex)
            {
                //Todo:gestion des exceptions
            }

  15. #35
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    pas de soucis
    Laisse moi juste le tester avant lol.
    Je le teste demain... merci!!!!!

  16. #36
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    Ca marche nikel!

    J'ai juste fait la modification suivante :
    C'est
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    utilisateur.Attributes["fond"].Value = r[2];
    et pas
    noeudAgence.FirstChild.Attributes["fond"].Value = r[2];
    Pour modifier l'attribut fond de l'utiilisateur s'il existe.

    Merci youtpout978!!!

    A présent, j'ai une autre question, mais je vais faire un nouveau post:

    Encore merci!!

  17. #37
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 066
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 066
    Points : 4 233
    Points
    4 233
    Par défaut
    de rien j'attends juste ma prime

  18. #38
    Membre habitué
    Profil pro
    Inscrit en
    Janvier 2004
    Messages
    488
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2004
    Messages : 488
    Points : 134
    Points
    134
    Par défaut
    Accepte ma sympathie et mon plus grand respect

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

Discussions similaires

  1. Lire et écrire dans un fichier XML mutualisé!
    Par Invité dans le forum VB.NET
    Réponses: 3
    Dernier message: 27/10/2014, 10h19
  2. lire et écrire dans un fichiers de signature XML
    Par masterdash dans le forum XML/XSL et SOAP
    Réponses: 0
    Dernier message: 17/01/2013, 21h19
  3. [XML/Glib/GTK+] Comment lire et écrire dans un fichier XML
    Par Skarsnick dans le forum GTK+ avec C & C++
    Réponses: 5
    Dernier message: 19/08/2009, 09h20
  4. [Xerces] Lire et écrire dans un fichier XML
    Par sKy_92310 dans le forum XML
    Réponses: 4
    Dernier message: 24/01/2009, 19h44
  5. [Rech. Comp.] Lire et écrire dans des fichiers XML
    Par Rodrigue dans le forum C++Builder
    Réponses: 4
    Dernier message: 26/08/2005, 20h48

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