/// <summary> /// Loads the xml configuration from a file /// </summary> /// <param name="configFile">The config file</param> /// <returns>The parsed config</returns> public static XMLConfigFile ParseXMLFile(FileInfo configFile) { if (configFile == null) throw new ArgumentNullException("configFile"); var root = new XMLConfigFile(); if (!configFile.Exists) return root; ConfigElement current = root; using (var reader = new XmlTextReader(configFile.OpenRead())) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "root") continue; if (reader.Name == "param") { string name = reader.GetAttribute("name"); if (name != null && name != "root") { var newElement = new ConfigElement(current); current[name] = newElement; current = newElement; } } else { var newElement = new ConfigElement(current); current[reader.Name] = newElement; current = newElement; } } else if (reader.NodeType == XmlNodeType.Text) { current.Set(reader.Value); } else if (reader.NodeType == XmlNodeType.EndElement) { if (reader.Name != "root") { current = current.Parent; } } } } return root; }
/// <summary> /// Constructs a new config element with the given parent. /// </summary> /// <param name="parent">the parent element of the newly created element</param> public ConfigElement(ConfigElement parent) { _parent = parent; }
/// <summary> /// Saves a single configuration element to an XML stream. /// </summary> /// <param name="writer">the xml writer to save to</param> /// <param name="name">the name for this element</param> /// <param name="element">the element to save</param> private static void SaveElement(XmlWriter writer, string name, ConfigElement element) { bool badName = IsBadXMLElementName(name); if (element.HasChildren) { if (name == null) name = "root"; if (badName) { writer.WriteStartElement("param"); writer.WriteAttributeString("name", name); } else { writer.WriteStartElement(name); } foreach (var entry in element.Children) { SaveElement(writer, entry.Key, entry.Value); } writer.WriteEndElement(); } else { if (name != null) { if (badName) { writer.WriteStartElement("param"); writer.WriteAttributeString("name", name); writer.WriteString(element.GetString()); writer.WriteEndElement(); } else { writer.WriteElementString(name, element.GetString()); } } } }
/// <summary> /// Creates and returns a new configuration element. /// </summary> /// <param name="parent">the parent element of the newly created element</param> /// <returns>the newly created config element</returns> private static ConfigElement GetNewConfigElement(ConfigElement parent) { return new ConfigElement(parent); }