This tutorial explains some tips for recovering values contained in an XML file. The published code is generic enough to be used in each of your projects!
It is often useful to store parameters in an XML file.
This file would have the following structure:
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <client name="idClient" value="12"/> <connection name="port" value="9825"/> </configuration> |
Save XML file in bin debug folder
To recover the value of the key “client”, it is very convenient to create a class and a dedicated method, like here:
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 |
public class ConfigManager { private static XmlTextReader txtReader = null; static ConfigManager() { try { FileStream fic = null; string AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string path = AppPath + @"\\param.xml"; fic = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); txtReader = new XmlTextReader(fic); } catch { } } /// <summary> /// Provided the reference customer identifier. /// </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; } } |
This method searches the entire XML file for the “Client” element. When it is found, then just look at its value.
Usage:
1 2 3 4 5 6 7 8 9 10 |
class Program { static void Main(string[] args) { Console.WriteLine( ConfigManager.getRefClientId()); Console.ReadLine(); } } |
How to Use XML File to Store Data and Retrieve Data