I have a table with an Xml column in Sql. All Xml files have a same schema and I want to merge some of this Xml together.
For example for X1:
<A>
<B>
<C id='101'>
<D id='102'>abcd</D>
</C>
<C id='103'>
<D id='104'>zxcv</D>
</C>
</B>
</A>
and X2:
<A>
<B>
<C id='101'>
<D id='102'>abcd</D>
<D id='501'>abef</D>
</C>
<C id='502'>
<D id='503'>efgh</D>
</C>
</B>
</A>
X1+X2=…
<A>
<B>
<C id='101'>
<D id='102'>abcd</D>
<D id='501'>abef</D>
</C>
<C id='103'>
<D id='104'>zxcv</D>
</C>
<C id='502'>
<D id='503'>efgh</D>
</C>
</B>
</A>
So which choice is the best and how:
- XQuery in Sql
- C# XDocument and XPath
- …
I think the best way to approach this is to write a class that merges two
XDocuments using the visitor pattern, with the distinction that we are always visiting nodes from the first document in parallel with nodes from the second document.The overall design would be something like:
A specific implementation could look like this:
If this code encounters something it can’t handle (e.g. nodes with the same id but different text; or comments), it throws an exception.