views:

925

answers:

3

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?

+13  A: 

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!

OJ
Any good XSLT editor?
Daud
We use xmlspy and there's a built-in editor in visual studio. I strongly recomend http://www.jenitennison.com/xslt/ and http://www.w3schools.com/xsl/xsl_languages.asp.
Goran
Michael Kay's *XSLT Programmer's Guide* (Wrox Press) is indispensable.
Robert Rossney
A: 

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

Rune Grimstad
+1  A: 

XElement.Add has an overload that takes object[].

List<string> elementNames = GetElementNames();

newOrder.Add(
  elementNames
    .Select(name => GetElement(name, oldOrder))
    .Where(element => element != null)
    .ToArray()
  );

//

public XElement GetElement(string name, XElement source)
{
  XElement result = null;
  XElement original = source.Elements(name).FirstOrDefault();
  if (original != null)
  {
    result = new XElement(name, (string)original)
  }
  return result;
}
David B