Best way to transform string [text][text][text][text][text] to XML?
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[] messageAr开发者_Python百科r = 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.XmlWriter
Here is an article with example: http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx
Alternatively use System.Xml.Linq.XDocument
and XDocument.Save()
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.save.aspx
In LINQ (with a dependency on .NET 4 or Silverlight 4 because of Zip):
string[] elementNames = new string[] { "first", "second", "third", "forth", "fifth" };
string input = "[text][text][text][text][text]";
XElement[] elements = input
.Substring(1, input.Length - 1)
.Split("][")
.Zip(elementNames, (value, element) => new XElement(element, value))
.ToArray();
XDocument document = new XDocument(
new XElement("Root", elements)
);
string xml = document.ToString();
精彩评论