Converting one XML document into another XML document

.net-3.5, c#, linq, xml

Solution

Use an XSLT transform instead. You can use the built-in .NET XslCompiledTransform to do the transformation. Saves you from having to type out stacks of code. If you don't already know XSL/XSLT, then learning it is something that'll bank you CV :)

Good luck!

Problem

I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and element names. Something like this: ``` XElement newOrder = new XElement("Order"); newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")), newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")), ............... ............... ...............and so on ``` The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?

Original source