// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections; using System.Text; using System.Xml; public class KeyValue { private string comm; private string key; private string val; public KeyValue(string comm, string key, string val) { this.comm = comm; this.key = key; this.val = val; } public string Comm { get { return comm; } set { comm = value; } } public string Key { get { return key; } set { key = value; } } public string Val { get { return val; } set { val = value; } } } public class Merger { private Hashtable lookup; private ArrayList store; private string lastcomment; public Merger() { lookup = new Hashtable(); store = new ArrayList(); } private void Process(XmlNode node) { if(node.NodeType == XmlNodeType.Element && node.Name == "add") { string k = node.Attributes["key"].Value; string v = node.Attributes["value"].Value; KeyValue kv = (KeyValue)lookup[k]; if(kv != null) { kv.Val = v; } else { kv = new KeyValue(lastcomment, k, v); store.Add(kv); lookup.Add(k, kv); } } foreach(XmlNode n in node.ChildNodes) { Process(n); } if(node.NodeType == XmlNodeType.Comment) { lastcomment = node.Value; } else { lastcomment = null; } } private void Load(string filename) { XmlDocument doc = new XmlDocument(); doc.Load(filename); Process(doc.DocumentElement); } public void Combine(string masterdoc, string doc) { Load(masterdoc); Load(doc); } public void Save(string newdoc) { XmlTextWriter wrt = new XmlTextWriter(newdoc, Encoding.UTF8); wrt.Formatting = Formatting.Indented; wrt.Indentation = 4; wrt.WriteStartDocument(); wrt.WriteStartElement("configuration"); wrt.WriteStartElement("appSettings"); foreach(KeyValue kv in store) { if(kv.Comm != null) { wrt.WriteComment(kv.Comm); } wrt.WriteStartElement("add"); wrt.WriteAttributeString("key", kv.Key); wrt.WriteAttributeString("value", kv.Val); wrt.WriteEndElement(); } wrt.WriteEndElement(); wrt.WriteEndElement(); wrt.WriteEndDocument(); wrt.Close(); } } class TestClass { public static void Main(string[] args) { Merger merg = new Merger(); merg.Combine(@"C:\doc1.xml", @"C:\doc2.xml"); merg.Save(@"C:\newdoc2.xml"); } }