We help IT Professionals succeed at work.
Get Started

Generating XML from a CSV

lm1189 asked
Last Modified: 2015-12-09
I'm writing code which iterates through a text file, and releases it in a certain XML format.  My intent is each line generate a separate XML file.  So for example, FileLoc would be the last column in the file, and the only Field Elements you would see, would be the ones on the line.  The number of elements purely dependent on the number of values on the line.

I'm having my most trouble figuring out how can I get my program to iterate on a line by line basis and use the header.  Essentially, it should read the first line (header), use that to name the attribute of the Field Element, push the value in the field and only populate values on a single line, write it to a file, then move to the next line and repeat the process.  

Below is my method and attached is the XML I'm working to match.

        private void processFile(string source, string output, char delimiter)

            int counter = 0;

            var lines = File.ReadAllLines(@source);
            string[] headers = lines[0].Split(delimiter).Select(x => x.Trim('\"')).ToArray();

                var xmlOut =

                new XElement("Import",
                    new XElement("Archive",
                        new XElement("Document","",new XAttribute("Pass","true"), 
                        new XElement("DocFile",new XAttribute("FileLoc",@"X:\MyFile.pdf"),
                        // BEGIN THE PARSING
                        new XElement("Fields",
                           lines.Where((line, index) => index > 0).Select(line =>
                            line.Split(delimiter).Select((column, index) => new XElement("Field", new XAttribute("value", column), new XAttribute("pass", "true"), new XAttribute("confidence", "0"), new XAttribute("Name", headers[index]))))))

                xmlOut.Save(@output + @"\Output-"+ counter + ".xml");

Open in new window

Any help is appreciated.
Watch Question
Software Engineer
This problem has been solved!
Unlock 1 Answer and 1 Comment.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE