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);
}