/// <summary> /// Parses a key value pair from an Xml node into the specified target. /// </summary> /// <remarks> /// The only reason we pass the Xml file name to this method is to be able to trace /// failures. /// </remarks> /// <param name="target">The target dictionary.</param> /// <param name="xn">The Xml node.</param> private void ParseKeyValuePair(IDictionary <string, string> target, XmlNode xn) { var key = string.Empty; var value = string.Empty; foreach (XmlAttribute xa in xn.Attributes) { if (AllowedKeyAttributeNames.Contains(xa.Name, StringComparison.ToStringComparer())) { key = xa.Value; } if (AllowedValueAttributeNames.Contains(xa.Name, StringComparison.ToStringComparer())) { value = xa.Value; } } if (string.IsNullOrEmpty(value)) { value = xn.InnerXml; } if (!string.IsNullOrEmpty(key)) { if (target.ContainsKey(key)) { This.Logger.Warning(string.Format( SR.DuplicateKeyInSettingsFile, key, CurrentFileName)); } else { target.Add(key, value); } } }
private void SerializeTo(IDictionary <string, string> source, XmlDocument doc) { XmlNode xnRoot = null; if (!doc.HasChildNodes) { doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", string.Empty)); xnRoot = doc.CreateElement(RootNodeName); doc.AppendChild(xnRoot); } else { foreach (XmlNode xn in doc.ChildNodes) { if (xn.Name.Equals(RootNodeName, StringComparison)) { xnRoot = xn; break; } } if (xnRoot == null) { xnRoot = doc.CreateElement(RootNodeName); doc.AppendChild(xnRoot); } } //We store the existing nodes for future use. var existingNodes = new Dictionary <string, XmlNode>(); if (xnRoot.HasChildNodes) { foreach (XmlNode xn in xnRoot.ChildNodes) { var key = string.Empty; var attributes = xn.Attributes; if ((attributes == null) || (attributes.Count == 0)) { continue; } foreach (XmlAttribute xa in xn.Attributes) { if (AllowedKeyAttributeNames.Contains(xa.Name, StringComparison.ToStringComparer())) { key = xa.Value; break; } } if (!existingNodes.ContainsKey(key) && !string.IsNullOrEmpty(key)) { existingNodes.Add(key, xn); } } } foreach (string key in source.Keys) { if (existingNodes.ContainsKey(key)) { var xn = existingNodes[key]; XmlAttribute xaValue = null; foreach (XmlAttribute xa in xn.Attributes) { if (AllowedValueAttributeNames.Contains(xa.Name, StringComparison.ToStringComparer())) { xaValue = xa; } } if (xaValue == null) { xaValue = doc.CreateAttribute(DefaultValueAttributeName); xn.Attributes.Append(xaValue); } xaValue.Value = source[key]; } else { XmlElement item = doc.CreateElement(ItemNodeName); XmlAttribute xaKey = doc.CreateAttribute(DefaultKeyAttributeName); XmlAttribute xaValue = doc.CreateAttribute(DefaultValueAttributeName); xaKey.Value = key; xaValue.Value = source[key]; item.Attributes.Append(xaKey); item.Attributes.Append(xaValue); xnRoot.AppendChild(item); } } }