Skip to content

Instantly share code, notes, and snippets.

@bforrest
Created January 21, 2012 16:17
Show Gist options
  • Save bforrest/1653187 to your computer and use it in GitHub Desktop.
Save bforrest/1653187 to your computer and use it in GitHub Desktop.
Use an xsd to transform a flat file into an xml document
using System;
using System.IO;
using System.Xml;
namespace FlatFileToXml
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static string schema = @"C:\Documents and Settings\Barry.Forrest\My Documents\Visual Studio Projects\FlatFileToXml\FileSchema.xml";
static string textData = @"C:\temp\emp_file.txt";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
XmlDocument xDoc = ConvertFlatFileToXml( schema, textData);
xDoc.Save("converted.xml");
}
/// <summary>
/// Read a flat file and generate an xml file based on the supplied schema file.
/// </summary>
/// <param name="schemaFile">Fully qualified path for the Schema used to create the Xml Document</param>
/// <param name="sourceFile">Fully qualified path for the text file to be converted.</param>
/// <returns>XmlDocument</returns>
public static XmlDocument ConvertFlatFileToXml(string schemaFile, string sourcePath)
{
string schemaPath = schemaFile;
string sourceFile = sourcePath;
XmlDocument docSchema = new XmlDocument();
docSchema.Load(schemaPath);
XmlNode tagName = docSchema.SelectSingleNode("DataRecord");
string outElementName = tagName.Attributes["tagname"].Value;
string rootTagName = tagName.Attributes["roottagname"].Value;
XmlDocument docTranslated = new XmlDocument();
XmlElement root = docTranslated.CreateElement(rootTagName);
docTranslated.AppendChild(root);
XmlNode attributeNode = docSchema.SelectSingleNode("DataRecord/Attributes");
using(StreamReader sr = new StreamReader( sourcePath))
{
string dataLine = string.Empty;
while ((dataLine = sr.ReadLine() )!= null)
{
XmlElement outElement = docTranslated.CreateElement(outElementName);
root.AppendChild(outElement);
foreach (XmlNode atNode in attributeNode.ChildNodes)
{
int start = Convert.ToInt32(atNode.Attributes["start"].Value);
int end = Convert.ToInt32(atNode.Attributes["end"].Value);
string name = atNode.Attributes["name"].Value;
string attributeValue = string.Empty;
attributeValue = dataLine.Substring(start, end - start).Trim().Replace("'", "''");
XmlAttribute outAttribute = docTranslated.CreateAttribute(name);
outAttribute.Value = attributeValue;
outElement.Attributes.Append(outAttribute);
}
}//end while
}//end using StreamReader
return docTranslated;
}//end ConvertFlatFileToXml
}
}
@chrisajames
Copy link

it would be really cool if you shared your xsd and your input file for completeness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment