Search code examples
c#xmllinq-to-xmlxelement

Convert flat text file to XML in C#


I have a .txt file and I have to change it in xml file. My .txt file is pipe-delimited ("|", vertical bar) flat text file. Like this:

169055|759656025621|Dos|Justamente Tres|Kill Rock Stars|256|PUNK|CD-JEWEL CASE|06/24/1996|D

Now I have to change this text file into xml file and also I have to add parent-child node for this xml. I have to use Linq to xml and XElement. Please help me out.


Solution

  • //path of your RDF file i.e. txt file used delimeter |
    
    String filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"RdfFile/RDF.txt");
    
    IEnumerable<String> source = File.ReadLines(filePath);
    
     XElement scans = new XElement("Test",
    
    
            from str in source
            let fields = str.Split('|')
            select new XElement("Product",
               new XAttribute("Action", FileName),
               new XAttribute("EnsureDefaultVariant", "1"),
               new XAttribute("ID", fields[0]),
    
    
    
                new XElement("Summary", fields[2]),
                new XElement("ImageFilenameOverride", fields[1])
    
    
                )
    
        );
    //path in which xml file you want to save result.
    
     String filePath_Xml = Path.Combine(HostingEnvironment.ApplicationPhysicalPath,
     @"XMLFile/RDF__Scans_Add_XMLFile.xml");
    
     scans.Save(filePath_Xml);