Ce tutoriel explique quelques astuces pour récupérer des valeurs contenues dans un fichier XML. Le code publié est assez générique pour pouvoir être utilisé dans chacun de vos projets !
Il est souvent utile de stocker des paramètres dans un fichier XML.
Ce fichier aurait la structure suivante :
<?xml version="1.0" encoding="utf-8" ?> <configuration> <client name="idClient" value="14"/> <connection name="port" value="1024"/> </configuration>
Pour récupérer la valeur de la clé « client », il est très pratique de créer une classe et une méthode dédiée, comme ici :
public class ConfigManager { private static System.Xml.XmlTextReader txtReader = null; static ConfigManager() { try { FileStream fic = null; string AppPath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly(). GetName().CodeBase); string path = AppPath + @".config"; fic = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); txtReader = new XmlTextReader(fic); } catch {} } /// <summary> /// Fourni l'identifiant du client de référence. /// </summary> /// <returns></returns> public static int getRefClientId() { try { while (txtReader.Read()) { XmlNodeType nType = txtReader.NodeType; if (nType == XmlNodeType.Element) { if (txtReader.Name.Equals("client") && txtReader.GetAttribute("name").Equals("idClient")) { string strValue = txtReader.GetAttribute("value"); return Convert.ToInt32(strValue); } } } } catch {} return -1; } }
Cette méthode parcours tout le fichier XML à la recherche de l'élément « Client ». Lorsque celui-ci est trouvé, il suffit alors de regarder sa valeur.
Grâce à une requête XPATH, il est possible d'accéder directement à l'élément recherché dans une structure XML.
Celle-ci pourrait avoir la forme suivante :
<?xml version="1.0" encoding="utf-8" ?> <configuration> <client id="14" desc="Identifiant du client"></client> <connection name="port" value="1024"/> </configuration>
Il est très pratique de créer une classe chargée de récupérer une liste de valeurs correspondantes à une requête XPath :
using System; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using System.Collections; /// <summary> /// Cette classe permet de retourner la valeur d'une expression XPAth /// </summary> class XPathNav { private static string XMLFilePath; static XPathNav() { XMLFilePath = @".MonAppli.exe.config"; } /// <summary> /// Méthode vierge permettant d'activer la classe statique /// </summary> public static void init(){} /// <summary> /// Récupère la valeur de l'attribut du noeud recherché dans le fichier de configuration /// </summary> /// <param name="xPathString">Expression XPath de recherche du noeud</param> /// <param name="attribute">Attribut à rechercher</param> /// <returns>Une ArrayList contenant la liste des attributs recherchés</returns> public static ArrayList SearchXPathNavigator(string xPathString, string attribute) { // Initilisation des variables XPathDocument xpathDoc; XPathNavigator xpathNavigator; XPathNodeIterator xpathNodeIterator; XPathExpression expr; ArrayList listOfAttributes = new ArrayList(); // Parcours du fichier XML try { xpathDoc = new XPathDocument(XMLFilePath); xpathNavigator = xpathDoc.CreateNavigator(); expr = xpathNavigator.Compile(xPathString); xpathNodeIterator = xpathNavigator.Select(expr); while (xpathNodeIterator.MoveNext()) { // On récupère l'attribut listOfAttributes.Add(xpathNodeIterator.Current.GetAttribute(attribute, "")); } } catch (Exception e) { } return listOfAttributes; } }
Récupérer la valeur est alors très simple, puisqu'il suffit d'appeler la méthode SearchXpathNavigator, en passant en paramètre la requête XPath :
ArrayList idClient = XPathNav.SearchXPathNavigator("/configuration/client", "id");