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 :

Lecture d'un fichier XML


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Par défaut Lecture d'un fichier XML
    Bonsoir,

    J'ai un fichier XML suivant:

    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
     
    <?xml version="1.0" encoding="utf-8" ?>
    <Config>
      <Data>
        <WorkingPath>./Data/</WorkingPath>
        <PublishPath></PublishPath>
      </Data>
      <AreasFields>
        <Field>id</Field>
      </AreasFields>
      <ProjectsFields>
        <Field>id</Field>
      </ProjectsFields>
      <RatesFields>
        <Field>id</Field>
        <Field>grade</Field>
      </RatesFields>
      <TimeFields>
        <Field>id</Field>
        <Field>project</Field>
        <Field>area</Field>
        <Field>initiatedDate</Field>
        <Field>dateEnded</Field>
        <Field>durationInMin</Field>
      </TimeFields>
      <TodosFields>
        <Field>id</Field>
        <Field>project</Field>
        <Field>area</Field>
        <Field>initiatedDate</Field>
        <Field>dueDate</Field>
      </TodosFields>
    </Config>

    Dont je veux pouvoir le lire. J'aimerais récupérer les differentes valeurs, et pour cela je vais le code suivant:

    Code C# : 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
     
    XmlTextReader XMLConfigFileReader = new XmlTextReader(@"./../../Config.xml");
                XmlDocument doc = new XmlDocument();
     
                int count = 0;
     
                while (XMLConfigFileReader.Read())
                {
     
                    MessageBox.Show(count.ToString());
     
                    if (XMLConfigFileReader.Name.Equals(__WORKINGPATH))
                        workingPath = doc.ReadNode(XMLConfigFileReader).InnerText;
     
                    if (XMLConfigFileReader.Name.Equals(__PUBLICPATH))
                        publicPath = doc.ReadNode(XMLConfigFileReader).InnerText;
     
                    if (XMLConfigFileReader.Name.Equals(__AREASFIELDS) | 
                        XMLConfigFileReader.Name.Equals(__PROJECTSFIELDS) |
                        XMLConfigFileReader.Name.Equals(__RATESFIELDS) |
                        XMLConfigFileReader.Name.Equals(__TIMEFIELDS) |
                        XMLConfigFileReader.Name.Equals(__TODOSFIELDS)
                        )
                    {
                        switch (XMLConfigFileReader.NodeType)
                        {
                            case XmlNodeType.Text:
                                MessageBox.Show("Text!");
                                break;
                            case XmlNodeType.Element:
                                MessageBox.Show("Element!");
                                MessageBox.Show(doc.ReadNode(XMLConfigFileReader).InnerText);
                                break;
                            default:
                                MessageBox.Show("Default!");
                                break;
                        }
                    }
                    count++;
                }

    Sauf que je n'arrive pas à bien récupérer les éléments :s

    Est-ce que quelqu'un aurait un tuto, un exemple de code ou une explication qui pourrait m'aider? Je pense qu'il s'agit d'un petit truc tout bête, mais ca fait un bon moment que je suis bloqué dessus...

    PS: les messagebox c'est pour débuger J'ai juste besoin de savoir comment faire pour récuperer chaque valeur, d'ou mon code:
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    MessageBox.Show(doc.ReadNode(XMLConfigFileReader).InnerText);

    Merci bien et bonne soirée!

    L.

  2. #2
    Membre chevronné Avatar de Jerede
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mai 2010
    Messages
    271
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mai 2010
    Messages : 271
    Par défaut
    Tu peut utiliser Linq, ça facilite les choses

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
     XDocument doc = XDocument.Load(@"./../../Config.xml");
     XElement root= doc.Root;
    String monWorkingPath = root.Element("Data").Element("WorkingPath").Value;

  3. #3
    Inactif  

    Homme Profil pro
    Ingénieur test de performance
    Inscrit en
    Décembre 2003
    Messages
    1 986
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur test de performance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Décembre 2003
    Messages : 1 986
    Par défaut
    Bonjour.

    Il y a beaucoup de façon de faire.

    Voici un exemple avec XPath en C++ managed (facilement transposable en C#, j'imagine).

    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
     
    String^ GetXmlszVal(XPathNavigator^ xPathNav, String^ szNode){
     
      String^ szRet = "ERROR";
     
      XPathNodeIterator^ xPathNod = xPathNav->Select(szNode);
     
      xPathNod->MoveNext();
     
      if(xPathNod->Count != 0)
        szRet = xPathNod->Current->Value;
     
      return szRet;
    }
     
    void ShowXmlValue(XPathNavigator^ xPathNav, String^ szNode){
     
      XPathNodeIterator^ xPathNod = xPathNav->Select(szNode + "/Field");
     
      while(xPathNod->MoveNext())
        MessageBox::Show(xPathNod->Current->Value);
    }
     
    void LoadXmlData(){
     
      XPathDocument^     xPathDoc = gcnew XPathDocument("Config.xml");
      XPathNavigator^     xPathNav = xPathDoc->CreateNavigator();
      XPathNodeIterator^ xPathNod = xPathNav->Select("/Config/Data");
     
      while(xPathNod->MoveNext()){
     
        MessageBox::Show(GetXmlszVal(xPathNod->Current, "./WorkingPath"));
        MessageBox::Show(GetXmlszVal(xPathNod->Current, "./PublishPath"));
      }
     
      xPathNod = xPathNav->Select("/Config");
     
      if(xPathNod->MoveNext()){
     
        ShowXmlValue(xPathNod->Current, "./AreasFields");
        ShowXmlValue(xPathNod->Current, "./ProjectsFields");
        ShowXmlValue(xPathNod->Current, "./RatesFields");
        ShowXmlValue(xPathNod->Current, "./TimeFields");
        ShowXmlValue(xPathNod->Current, "./TodosFields");
      }
    }

  4. #4
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Par défaut
    Citation Envoyé par Jerede Voir le message
    Tu peut utiliser Linq, ça facilite les choses

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
     XDocument doc = XDocument.Load(@"./../../Config.xml");
     XElement root= doc.Root;
    String monWorkingPath = root.Element("Data").Element("WorkingPath").Value;
    Ok. Mais ça veut dire que je dois lui indiqué de manière statique les éléments parents et enfants alors?

    Sinon j'aime bien cette solution

    Citation Envoyé par moldavi Voir le message
    Bonjour.

    Il y a beaucoup de façon de faire.

    Voici un exemple avec XPath en C++ managed (facilement transposable en C#, j'imagine).

    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
     
    String^ GetXmlszVal(XPathNavigator^ xPathNav, String^ szNode){
     
      String^ szRet = "ERROR";
     
      XPathNodeIterator^ xPathNod = xPathNav->Select(szNode);
     
      xPathNod->MoveNext();
     
      if(xPathNod->Count != 0)
        szRet = xPathNod->Current->Value;
     
      return szRet;
    }
     
    void ShowXmlValue(XPathNavigator^ xPathNav, String^ szNode){
     
      XPathNodeIterator^ xPathNod = xPathNav->Select(szNode + "/Field");
     
      while(xPathNod->MoveNext())
        MessageBox::Show(xPathNod->Current->Value);
    }
     
    void LoadXmlData(){
     
      XPathDocument^     xPathDoc = gcnew XPathDocument("Config.xml");
      XPathNavigator^     xPathNav = xPathDoc->CreateNavigator();
      XPathNodeIterator^ xPathNod = xPathNav->Select("/Config/Data");
     
      while(xPathNod->MoveNext()){
     
        MessageBox::Show(GetXmlszVal(xPathNod->Current, "./WorkingPath"));
        MessageBox::Show(GetXmlszVal(xPathNod->Current, "./PublishPath"));
      }
     
      xPathNod = xPathNav->Select("/Config");
     
      if(xPathNod->MoveNext()){
     
        ShowXmlValue(xPathNod->Current, "./AreasFields");
        ShowXmlValue(xPathNod->Current, "./ProjectsFields");
        ShowXmlValue(xPathNod->Current, "./RatesFields");
        ShowXmlValue(xPathNod->Current, "./TimeFields");
        ShowXmlValue(xPathNod->Current, "./TodosFields");
      }
    }
    Je vais en premier tenter l'autre solution, et si nécessaire je garde celle-là dans ma tête

    Merci beaucoup en tout cas

    L.

  5. #5
    Membre éclairé
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Par défaut
    J'ai pu lire correctement mon fichier avec LINQ to XML, mais par contre c'est assez complexe pour récupérer les valeurs sont aller forcément donner les noms des enfants.

    Je me suis fais un petit programme pour effectuer des test suivant (le fichier XML est le même):

    Code C# : 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
     
    static void Main(string[] args)
            {
                try
                {
                    Console.WriteLine("\nProgram made to test XML functions\n");
                    Console.Write("Opening file...");
                    XmlTextReader XmlFile = new XmlTextReader(@"./../../TestFile.xml");
                    Console.WriteLine("Opened!");
                    Console.Write("Reading file...\n\n");
                    ReadXMLFile();
                    Console.WriteLine("\n\nReading done!");
                    Console.Read();
                }
                catch (Exception e)
                {
                    Console.Beep();
                    Console.WriteLine("ERROR - Detailed err msg: " + e.Message);
                    Console.Read();
                }
            }
     
            static void ReadXMLFile()
            {
                XDocument xmlFile = XDocument.Load(@"./../../TestFile.xml");
                XElement parent = xmlFile.Root;
     
                var MyDataConfig = from d in parent.Elements() select d;
     
                foreach (var path in MyDataConfig)
                {
     
                    //Console.WriteLine(path.FirstAttribute.ToString());
                    Console.WriteLine("First");
                    switch (path.Parent.FirstNode.Parent.ToString())
                    {
                        case "WorkingPath":
                            Console.WriteLine("Passed!!!!!");
                            break;
                        default:
                            break;
                    }
                    //Console.WriteLine(path.Element("WorkingPath").Value);
                    Console.WriteLine("Last\n");
                }
            }

    Mais du coup, je suis bloqué dans le foreach pour récupérer les valeurs sans forcément aller lui dire "WorkingPath", PublishPath", Field... dailleurs comment ça va se passer avec ce champ vu que j'en ai plusieurs, il va me faire une erreur je pense non?

  6. #6
    Membre chevronné Avatar de Jerede
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mai 2010
    Messages
    271
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Mai 2010
    Messages : 271
    Par défaut
    Tu n'est pas obligé d'utilisé .Element(String Name) tu peut utiliser .Elements() qui te renvois une collection d'élement
    Dans ton cas .Elements() de root te renverra une Collection contenant les Xelement :
    <Data>
    <AreasFields>
    <ProjectsFields>
    <RatesFields>
    <TimeFields>
    <TodosFields>


    contenant chacun une autre collection de Xelement

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Problème de lecture d'un fichier XML d'InfoPath
    Par snadus dans le forum InfoPath
    Réponses: 7
    Dernier message: 06/06/2006, 14h45
  2. Lecture d'un fichier XML de config avec Java
    Par cofy dans le forum Format d'échange (XML, JSON...)
    Réponses: 6
    Dernier message: 31/01/2006, 15h54
  3. Problème de lecture dans un fichier xml
    Par Pyra dans le forum Langage
    Réponses: 2
    Dernier message: 18/12/2005, 00h13
  4. Probleme de lecture d'un fichier XML
    Par chleuh dans le forum Langage
    Réponses: 8
    Dernier message: 30/08/2005, 12h04
  5. [C#] [XML] Lecture d'un fichier XML => Combobox
    Par Chad`Chiwa dans le forum Windows Forms
    Réponses: 8
    Dernier message: 09/03/2005, 08h57

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