Transforming an XML document and splicing its contents with another. - CSharp XML

CSharp examples for XML:Transform

Description

Transforming an XML document and splicing its contents with another.

Demo Code

using System;//from  ww w.j a v a 2  s  .  co  m
using System.Linq;
using System.Xml.Linq;

class MainClass
{
   private static readonly XNamespace employeesOld = "http://www.deitel.com/employeesold";
   private static readonly XNamespace employeesNew = "http://www.deitel.com/employeesnew";

   static void Main(string[] args)
   {
      XDocument newDocument = XDocument.Load("employeesNew.xml");
      XDocument oldDocument = XDocument.Load("employeesOld.xml");

      oldDocument = TransformDocument(oldDocument);
      SaveFinalDocument(newDocument, oldDocument);
   }
   private static XDocument TransformDocument(XDocument document)
   {
      var newDocumentRoot = new XElement(employeesNew + "employeelist",
         from employee in document.Root.Elements()
         select TransformEmployee(employee));

      return new XDocument(newDocumentRoot); // return new document
   }

   private static XElement TransformEmployee(XElement employee)
   {
      XNamespace old = employeesOld; // shorter name
      string firstName = employee.Element(old + "firstname").Value;
      string lastName = employee.Element(old + "lastname").Value;
      string salary = employee.Element(old + "salary").Value;

      return new XElement(employeesNew + "employee", new XAttribute("name", firstName + " " + lastName), new XAttribute("salary", salary));
   }
   private static void SaveFinalDocument(XDocument document1, XDocument document2)
   {
      var root = new XElement(employeesNew + "employeelist");

      // fill with the elements contained in the roots of both documents
      root.Add(document1.Root.Elements());
      root.Add(document2.Root.Elements());

      root.Save("output.xml"); // save document to file
   }
}

Result


Related Tutorials