Skip to content

Commit 89b7626

Browse files
committed
fix(XMLPatch): add checks to prevent duplicate elements during addition
1 parent a6f41a0 commit 89b7626

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

XMLPatch/Program.cs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,21 +386,61 @@ private static void ApplyAdd(XElement addElement, XElement originalRoot)
386386
Logger.Debug($"Cloned element: {clonedInfo}");
387387
if (pos == "before")
388388
{
389+
if (
390+
targetElement
391+
.Parent!.Elements()
392+
.Any(e => e.Name == cloned.Name && e.Attributes().All(a => cloned.Attribute(a.Name)?.Value == a.Value))
393+
)
394+
{
395+
Logger.Warn($"Element '{clonedInfo}' already exists in '{parentInfo}'. Skipping.");
396+
continue;
397+
}
389398
targetElement.AddBeforeSelf(cloned);
390399
Logger.Info($"Added new element '{clonedInfo}' before '{targetInfo}' in '{parentInfo}'.");
391400
}
392401
else if (pos == "after")
393402
{
403+
if (
404+
targetElement
405+
.Parent!.Elements()
406+
.Any(e => e.Name == cloned.Name && e.Attributes().All(a => cloned.Attribute(a.Name)?.Value == a.Value))
407+
)
408+
{
409+
Logger.Warn($"Element '{clonedInfo}' already exists in '{parentInfo}'. Skipping.");
410+
continue;
411+
}
394412
targetElement.AddAfterSelf(cloned);
395413
Logger.Info($"Added new element '{clonedInfo}' after '{targetInfo}' in '{parentInfo}'.");
396414
}
397415
else if (pos == "prepend")
398416
{
417+
if (
418+
targetElement
419+
.Elements()
420+
.Any(e =>
421+
e.Name == cloned.Name && e.Attributes().All(a => a.Name == "_source" || cloned.Attribute(a.Name)?.Value == a.Value)
422+
)
423+
)
424+
{
425+
Logger.Warn($"Element '{clonedInfo}' already exists in '{targetInfo}'. Skipping.");
426+
continue;
427+
}
399428
targetElement.AddFirst(cloned);
400429
Logger.Info($"Prepended new element '{clonedInfo}' to '{targetInfo}'.");
401430
}
402431
else if (pos == "append")
403432
{
433+
if (
434+
targetElement
435+
.Elements()
436+
.Any(e =>
437+
e.Name == cloned.Name && e.Attributes().All(a => a.Name == "_source" || cloned.Attribute(a.Name)?.Value == a.Value)
438+
)
439+
)
440+
{
441+
Logger.Warn($"Element '{clonedInfo}' already exists in '{targetInfo}'. Skipping.");
442+
continue;
443+
}
404444
targetElement.Add(cloned);
405445
Logger.Info($"Appended new element '{clonedInfo}' to '{targetInfo}'.");
406446
}
@@ -472,8 +512,9 @@ private static void ApplyReplace(XElement replaceElement, XElement originalRoot)
472512
}
473513
else if (targetObj is XAttribute attr)
474514
{
515+
var oldValue = attr.Value;
475516
attr.Value = replaceElement.Value;
476-
Logger.Info($"Replaced value of attribute '{attr.Name}' with '{replaceElement.Value}'.");
517+
Logger.Info($"Replaced value of attribute '{attr.Name}' from '{oldValue}' to '{replaceElement.Value}'.");
477518
}
478519
}
479520
}

0 commit comments

Comments
 (0)