Created
April 19, 2018 20:53
-
-
Save MCord/914fc3412156a2663b49733971524541 to your computer and use it in GitHub Desktop.
C# implemtation to deteministically merge an xml into another.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class XmlMerge | |
{ | |
public static bool MergeElements(XElement left, XElement right) | |
{ | |
var hasChanges = MergeAttributes(left, left.Attributes(), right.Attributes()); | |
if (!left.HasElements && !right.HasElements) | |
{ | |
if (left.Value == right.Value) | |
{ | |
return hasChanges; | |
} | |
left.Value = right.Value; | |
return true; | |
} | |
var todo = new List<XElement>(left.Elements()); | |
foreach (var xElement in right.Elements()) | |
{ | |
if (Find(todo, x=> x.Name.LocalName == xElement.Name.LocalName, out XElement match)) | |
{ | |
todo.Remove(match); | |
hasChanges = MergeElements(match, xElement) || hasChanges; | |
continue; | |
} | |
hasChanges = true; | |
left.Add(xElement); | |
} | |
foreach (var t in todo) | |
{ | |
hasChanges = true; | |
t.Remove(); | |
} | |
return hasChanges; | |
} | |
private static bool MergeAttributes(XElement parent, IEnumerable<XAttribute> leftAttributes, IEnumerable<XAttribute> rightAttributes) | |
{ | |
var hasChanges = false; | |
var todo = new List<XAttribute>(leftAttributes); | |
foreach (var att in rightAttributes) | |
{ | |
if (Find(todo, x=> x.Name.LocalName == att.Name.LocalName, out XAttribute match)) | |
{ | |
if (match.Value != att.Value) | |
{ | |
hasChanges = true; | |
match.Value = att.Value; | |
} | |
todo.Remove(match); | |
continue; | |
} | |
hasChanges = true; | |
parent.Add(att); | |
} | |
foreach (var xAttribute in todo) | |
{ | |
hasChanges = true; | |
xAttribute.Remove(); | |
} | |
return hasChanges; | |
} | |
private static bool Find<T>(IEnumerable<T> list, Func<T, bool> predicate,out T match) | |
{ | |
foreach (var item in list) | |
{ | |
if (predicate(item)) | |
{ | |
match = item; | |
return true; | |
} | |
} | |
match = default(T); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is useful if you want to sync an xml file from an external reference while preventing xml reordering. an example would be to keep unnecessary changes like reordering out of source control.