Search code examples
c#xmlcsvxelement

Create XML from multiple CSV's in multiple folders


The whole point of what I am doing is I need to create a master XML from multiple CSV files located in multiple subfolders within one master folder.

This is what I am using right now, but it seems to overwrite and creates an xml for only the last CSV...

String AudioDir = @"C:\XMLFILES";
        DirectoryInfo AudiodirInfo = new DirectoryInfo(AudioDir);
        if (AudiodirInfo.Exists == false)
        {
            Directory.CreateDirectory(AudioDir);
        }

        List<String> AudioXMLFiles = Directory.GetFiles(@"C:\LOGGER AUDIO", "*.csv*", SearchOption.AllDirectories).ToList();
        XElement audxml = null;
        foreach (string file in AudioXMLFiles)
        {
            string[] lines2 = File.ReadAllLines(file);
           audxml = new XElement("root",
           from str in lines2
           let columns = str.Split(',')
           select new XElement("recording_info",
                   new XElement("recorded_accound_id", columns[1]),
                   new XElement("date_created_ts", String.Format("{0:####-##-##  ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))),                                    
                   new XElement("recorded_cid", columns[9]),//1
                   new XElement("recording_tag", columns[1]),
                   new XElement("filename", columns[1] + "_" + columns[2] + "_" + columns[3]),
                   new XElement("record", columns[3]),//Record in TimeoutException format
                   new XElement("from_caller_id", columns[10] + "  <" + columns[8] + ">")



               ));


        }
        audxml.Save(@"C:\XMLFile.xml");

Solution

  • You're overwriting audxml in each iteration of the foreach. What you probably want is to create a root node outside the loop and then add each file's xml output to that root node.

    XElement audxml = new XElement("root");
    
    foreach (string file in AudioXMLFiles)
        {
            string[] lines2 = File.ReadAllLines(file);
           XElement filexml = new XElement("root",
           from str in lines2
           let columns = str.Split(',')
           select new XElement("recording_info",
                   new XElement("recorded_accound_id", columns[1]),
                   new XElement("date_created_ts", String.Format("{0:####-##-##  ##:##:##}", Convert.ToInt64(columns[2] + columns[3]))),                                    
                   new XElement("recorded_cid", columns[9]),//1
                   new XElement("recording_tag", columns[1]),
                   new XElement("filename", columns[1] + "_" + columns[2] + "_" + columns[3]),
                   new XElement("record", columns[3]),//Record in TimeoutException format
                   new XElement("from_caller_id", columns[10] + "  <" + columns[8] + ">")
               ));
    
               audXml.Add(fileXml);
        }
        audxml.Save(@"C:\XMLFile.xml");