I\'m not quite sure how to ask this, or if this even exists, but I have a need to merge two XElements with one taking precendence over the other, to become just one element.
Here's a console app that produces the result listed in your question. It uses recursion to process each sub element. The one thing it doesn't check for is child elements that appear in Elem2
that aren't in Elem1
, but hopefully this will get you started towards a solution.
I'm not sure if I would say this is the best possible solution, but it does work.
Module Module1
Function MergeElements(ByVal Elem1 As XElement, ByVal Elem2 As XElement) As XElement
If Elem2 Is Nothing Then
Return Elem1
End If
Dim result = New XElement(Elem1.Name)
For Each attr In Elem1.Attributes
result.Add(attr)
Next
Dim Elem1AttributeNames = From attr In Elem1.Attributes _
Select attr.Name
For Each attr In Elem2.Attributes
If Not Elem1AttributeNames.Contains(attr.Name) Then
result.Add(attr)
End If
Next
If Elem1.Elements().Count > 0 Then
For Each elem In Elem1.Elements
result.Add(MergeElements(elem, Elem2.Element(elem.Name)))
Next
Else
result.Value = Elem1.Value
End If
Return result
End Function
Sub Main()
Dim Elem1 =
Center
Gordie Howe
Dim Elem2 =
Wayne Gretzky
Console.WriteLine(MergeElements(Elem1, Elem2))
Console.ReadLine()
End Sub
End Module
Edit: I just noticed that the function was missing As XElement
. I'm actually surprised that it worked without that! I work with VB.NET every day, but it has some quirks that I still don't totally understand.