I have a string in the format of [text][text][text][text][text] and I want to transform it to XML syntax. My code below does this but I wonder if/how I can improve it, would you do it in a different way?
TextReader tr = new StreamReader(@"C:\values.txt");
string message = tr.ReadToEnd().Trim().Replace("][", "|").Replace("[", "").Replace("]", "");
tr.Close();
string[] nodeStart = { "<firstNode>", "<secondNode>", "<thirdNode>", "<fourthNode>", "<fifthNode>" };
string[] nodeEnd = { "</firstNode>", "</secondNode>", "</thirdNode>", "</fourthNode>", "</fifthNode>" };
string[] messageArr = message.Split('|');
StringBuilder sb = new StringBuilder();
sb.AppendLine("<rootNode>");
for(int i = 0; i < messageArr.Length; i++)
{
sb.AppendLine(String.Format("{0}{1}{2}", nodeStart[i], messageArr[i], nodeEnd[i]));
}
sb.AppendLine("</rootNode>");
Console.WriteLine(sb);
Console.ReadLine();
The output/format of the xml is simplified for this example
Thanks in advance.
To support my comment:
Use
System.Xml.XmlWriterHere is an article with example:
http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx
Alternatively use
System.Xml.Linq.XDocumentandXDocument.Save()http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.save.aspx