XML lookup table [modified]
-
Hi, I want to store a set of codes in an XML file and read the contents. I want each object to be a item consisting of a name and a code, so that I can put the name in and get the corresponding code out. What's a simple and efficient way of doing this? I can't use my web.config as there may be many codes. Thanks :)
-
Hi, I want to store a set of codes in an XML file and read the contents. I want each object to be a item consisting of a name and a code, so that I can put the name in and get the corresponding code out. What's a simple and efficient way of doing this? I can't use my web.config as there may be many codes. Thanks :)
Assuming your object value can be rendered as a string, XmlTextWriter and XPath are your simplest tools. A simple WriteElementString to write each object with the element name for your object name, and the element value your object value. Then for reading you load the file into an XmlDocument, and use an XPath query for the element with your object name, and get its value. public static void Write() { using (XmlTextWriter tw = new XmlTextWriter(myFileName, System.Text.Encoding.Default)) { tw.WriteStartDocument(); tw.WriteElementString("ObjectName", "ObjectValue"); tw.WriteEndDocument(); } } public static void Read() { XmlDocument xdoc = new XmlDocument(); xdoc.Load(myFileName); XmlNode myObject = xdoc.SelectSingleNode("ObjectName"); string myValue = ""; if (myObject != null) myValue = myObject.InnerText; }
-
Assuming your object value can be rendered as a string, XmlTextWriter and XPath are your simplest tools. A simple WriteElementString to write each object with the element name for your object name, and the element value your object value. Then for reading you load the file into an XmlDocument, and use an XPath query for the element with your object name, and get its value. public static void Write() { using (XmlTextWriter tw = new XmlTextWriter(myFileName, System.Text.Encoding.Default)) { tw.WriteStartDocument(); tw.WriteElementString("ObjectName", "ObjectValue"); tw.WriteEndDocument(); } } public static void Read() { XmlDocument xdoc = new XmlDocument(); xdoc.Load(myFileName); XmlNode myObject = xdoc.SelectSingleNode("ObjectName"); string myValue = ""; if (myObject != null) myValue = myObject.InnerText; }
That's great, thanks :)