We help IT Professionals succeed at work.

Converting a txt file to xml

TechIsaac
TechIsaac used Ask the Experts™
on
I have to code a c# solution to convert a txt file to xml using vs 2017.

What is the best way to do this task
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018

Commented:
https://askubuntu.com/questions/581265/how-can-i-convert-a-csv-file-to-xml

Open in new window

provides a good overview.

The approach is simple.

1) Define your XML output format.

2) Write code to ingest your data, format it, output your XML.

Note: Because every XML file contains a unique format, you'll have to cobble together your own XML generation.

Tip: Doing this in C# will likely take much more time, than using a tool like PERL which is built to work with strings.
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Hi TechIsaac;

There is no built in out of the box solution to something like this.

What does the text file look like and what is the schema of the XML file to be created look like?

Fernando
TechIsaacIT Contracting

Author

Commented:
Below is a simple csv and xml file.

The shops preference is c#
csv

Jack,35,United States
Jill,22,United Kingdom

xml
 
<?xml version="1.0"?>
<Customers>
  <Customer>
    <Name>Jack</Name>
    <Age>35</Age>
    <Country>United States</Country>
 </Customer>
 <Customer>
    <Name>Jill</Name>
    <Age>22</Age>
    <Country>United Kingdom</Country>
 </Customer>
</Customers>

Commented:
Step 1: Set up a new class to represent each individual customer:
public class Customer
{
  public string Name { get; set; }
  public string Age { get; set; }
  public string Country { get; set; }
}

Open in new window


Step 2: Create a List<Customer> as a container for all the customers:
var customers = new List<Customer>();

Open in new window


Step 3: Get a CSV parsing library, like this one:
https://github.com/jhilgeman/CSV/blob/master/CSV.cs

Step 4: Use the event "onRecordRead" from the above library to create an event handler that maps the CSV data to a new instance of Customer:
            var csvReader = new MyUtilities.CSV("C:\\datafile.csv");
            csvReader.onRecordRead += CsvReader_onRecordRead;
            csvReader.ReadAllRecords();
...
        private void CsvReader_onRecordRead(object sender, MyUtilities.CSV csv, List<string> record, int validationResult)
        {
            // Create a new instance of a Customer model and map our CSV data to it
            var customer = new Customer()
            {
                Name = record[0],
                Age = record[1],
                Country = record[2]
            };

            // Add it to our List container
            customers.Add(customer);
        }

Open in new window


Step 5: After the CSV file is parsed and transformed into the List of Customer objects, then just use XML serialization to save the list into an XML file. This is a pretty good tutorial to follow:
https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part

That's it.

if you want to see the all the main code (except for Step 5), here's a sample:
    public partial class MainWindow : Window
    {
        // Container for all our Customers
        public List<Customer> customers = new List<Customer>();

        public MainWindow()
        {
            InitializeComponent();

            // Initialize CSV reader and run it
            var csvReader = new MyUtilities.CSV("C:\\datafile.csv");
            csvReader.onRecordRead += CsvReader_onRecordRead;
            csvReader.ReadAllRecords();

           // Step 5 would go here
        }

        private void CsvReader_onRecordRead(object sender, MyUtilities.CSV csv, List<string> record, int validationResult)
        {
            // Create a new instance of a Customer model and map our CSV data to it
            var customer = new Customer()
            {
                Name = record[0],
                Age = record[1],
                Country = record[2]
            };

            // Add it to our List container
            customers.Add(customer);
        }

        // Model representing each individual customer
        public class Customer
        {
            public string Name { get; set; }
            public string Age { get; set; }
            public string Country { get; set; }
        }
    }

Open in new window

Retired
Distinguished Expert 2017
Commented:
Hi TechIsaac;

The following code will do what you are looking for. Please note add a reference to the Microsoft.VisualBasic dll
using System;
using System.Windows.Forms;
using System.Xml.Linq;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "uft-8", "true"), new XElement("Customers"));
            // Change the "csvData.txt" to the path and name of your data file
            using (var dataReader = new Microsoft.VisualBasic.FileIO.TextFieldParser("csvData.txt"))
            {
                dataReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
                dataReader.SetDelimiters(",");
                dataReader.TrimWhiteSpace = true;

                while (!dataReader.EndOfData)
                {
                    string[] fields = dataReader.ReadFields();
                    XElement customer = new XElement("Customer",
                        new XElement("Name", fields[0]), 
                        new XElement("Age", fields[1]), 
                        new XElement("Country", fields[2])
                    );

                    xdoc.Root.Add(customer);
                }

                // Uncomment the next line to save to file system changing file path and name
                // xdoc.Save("xmlResults.xml");
                // Uncomment the next line to save to a variable 
                // string xmlData = xdoc.ToString();

            }
        }
    }
}

Open in new window


Running the above code will produce the following results.
<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer>
    <Name>Jack</Name>
    <Age>35</Age>
    <Country>United States</Country>
  </Customer>
  <Customer>
    <Name>Jill</Name>
    <Age>22</Age>
    <Country>United Kingdom</Country>
  </Customer>
</Customers>

Open in new window

TechIsaacIT Contracting

Author

Commented:
Thanks Fernando,

This is exactly what I needed.

Isaac
TechIsaacIT Contracting

Author

Commented:
Thanks so much.  This is what I needed.
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Not a problem TechIsaac, glad to help.