简体   繁体   中英

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[] 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.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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM