C# from text file to XML with structure

Markus Freitag 3,786 Reputation points
2021-01-15T13:14:40.893+00:00

Hello,

I get a list of numbers in an array.
What is the easiest way to create an XML file from this?

AAA5SUU
AAA5SUV
AAA5SUW
AAA5SUX
AAA5SUY
AAA5SUZ
AAA5SV0
AAA5SV1
AAA5SV2
AAA5SV3
AAA5SV4
AAA5SV5
AAA5SV6
AAA5SV7
AAA5SV8
AAA5SV9
AAA5SVA
AAA5SVB
AAA5SVC
AAA5SVD
AAA5SVE
AAA5SVF
AAA5SVG
AAA5SVH
AAA5SVI
AAA5SVJ
AAA5SVK
AAA5SVL



<SERIALS>
  <POS index="1" content="AAA5SUU" processed="false"/>
  <POS index="2" content="AAA5SUV" processed="false"/>
  <POS index="3" content="AAA5SUW" processed="false"/>


  <POS index="1000" content="AAA5SVL" processed="false"/>
</SERIALS>

Save it on harddisk C:\ProcessData\2021-01-15.xml

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 25,026 Reputation points
    2021-01-17T05:32:44.57+00:00

    By using LINQ to XML.
    Additionally, you have a full control for the XML file on the following:

    • indented or not
    • spaces or tabs
    • omit XML prolog or not
    • Byte Order Mark (BOM) or not
    • Etc.

    c#

    void Main()
    {
     const string ROOT = "SERIALS";
     const string inputXMLfile = @"c:\...\Input.txt";
     const string outputXMLfile = @"c:\...\Output2.xml";
    
     int importNumber = 1;
    
     // construct new XML document
     XDocument newXDoc = new XDocument(new XElement(ROOT));
    
     using (StreamReader sr = new StreamReader(inputXMLfile))
     {
     while (sr.Peek() > -1)
     {
     newXDoc.Root.Add(new XElement("POS",
     new XAttribute("index", importNumber),
     new XAttribute("content", sr.ReadLine()),
     new XAttribute("processed", "false")
     ));
     importNumber++;
     }
     }
    
     // save XML document
     XmlWriterSettings settings = new XmlWriterSettings();
     settings.Indent = true;
     settings.IndentChars = "\t";
     settings.OmitXmlDeclaration = true;
     // to remove BOM
     settings.Encoding = new UTF8Encoding(false);
    
     using (XmlWriter writer = XmlWriter.Create(outputXMLfile, settings))
     {
     newXDoc.Save(writer);
     }
     Console.WriteLine("File '{0}' has been created.", outputXMLfile);
    }
    

1 additional answer

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2021-01-16T19:12:26.753+00:00

    Try something like this. I made a file importMe.Text with the values posted above. each line creates a new pos with the content and then I serialize the list of Pos into an xml file

     class Program
      {
        static void Main(string[] args)
           {
              int importNumber = 1;
              List<Pos> items = new List<Pos>();
              using (StreamReader sr = new StreamReader("importMe.txt"))
              {
                   while (sr.Peek()>-1)
                   {
                         items.Add(new Pos()
                        {
                            index=importNumber,
                            content=sr.ReadLine(),
                           processed = false
                       });
                    importNumber++;
                }
            }
    
            XmlSerializer ser = new XmlSerializer(typeof(List<Pos>));
    
            using (FileStream fs = new FileStream(@"export.xml", FileMode.Create))
            {
                ser.Serialize(fs, items);
            }
        }
    }
    
    
    public class Pos
    {
        [XmlAttribute]
        public int index { get; set; }
        [XmlAttribute]
        public string content { get; set; }
        [XmlAttribute]
        public bool processed { get; set; }
    }
    
    0 comments No comments