Link to home
Create AccountLog in
Avatar of Isaac Johnson
Isaac JohnsonFlag for United States of America

asked on

Converting a txt file to xml

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
Avatar of David Favor
David Favor
Flag of United States of America image

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.
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
Avatar of Isaac Johnson

ASKER

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>
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

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Thanks Fernando,

This is exactly what I needed.

Isaac
Thanks so much.  This is what I needed.
Not a problem TechIsaac, glad to help.