Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting one XML document into another XML document

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?

like image 388
Malik Daud Ahmad Khokhar Avatar asked Dec 03 '22 16:12

Malik Daud Ahmad Khokhar


2 Answers

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!

like image 170
OJ. Avatar answered Dec 27 '22 15:12

OJ.


Use an XSLT transformation to translate your old xml document into the new format.

like image 39
Rune Grimstad Avatar answered Dec 27 '22 13:12

Rune Grimstad