XML to XML – Translating XML with C#

Working with XML documents is the new way of EDI in today’s business work.  XML to XML provides a way to not only translate data that you want to work with, but also provides a way to store extreme amounts of information in a structured manner.  In this article I will discuss how to use XML in two forms, XML to XML or moving one XML document to another XML document and translating it along the way and XML to Object.  XML to Objects will be used in the XML to XML process but it will also help with keeping your XML uniform as well.

The most important piece in XML to XML is uniform documents

Starting out with a fresh document is very important in being successful in translation.  Here is an example of a simple yet effective XML document:

xml to xml job definition

The first part of XML to XML is to load the document into a XmlDocument file.  We do this through instantiating a XmlDocument and calling the Load method targeting our file.  The XmlDocument will be used to populate our new document and then write out to finish our XML to XML process.

            XmlDocument xmlJobDoc = new System.Xml.XmlDocument();
            XmlDocument xmlLoadDocument = new System.Xml.XmlDocument();
            XmlNode xmlJobNode;
            XmlAttribute xmlAttribute;
            XmlNode xmlRootNode = xmlLoadDocument.CreateElement("Root");
            xmlJobDoc.Load("JobDefinition.xml");
            for (int i = 0; i < 2; i++)
            {
                xmlJobNode = xmlLoadDocument.CreateElement("TruckRun");
                xmlAttribute = xmlLoadDocument.CreateAttribute("JobNumber");
                xmlAttribute.Value = i.ToString();
                xmlJobNode.Attributes.Append(xmlAttribute);

                xmlJobNode.AppendChild(xmlLoadDocument.ImportNode(xmlJobDoc.DocumentElement,true));
                xmlRootNode.AppendChild(xmlJobNode);
            }
            xmlLoadDocument.AppendChild(xmlRootNode);
            xmlLoadDocument.Save("JobFile.xml");

Xml to Xml utilizing Xml ImportNode Command

This will utilize the Xml to Xml specific command called ImportNode. ImportNode is powerful as it allows you to copy one specific section of an Xml document to another Xml document or use the Xml to Xml functionality as if you were copy and pasting. To finish up the Xml to Xml translation, we utilize the Save method on the Xml document and push the information to the specified file.  If you would like to learn more about translating Xml documents from Xml to Xml or other Xml processing capabilities of Microsoft dotNet Framework, check out this MSDN article.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>