简体   繁体   中英

How to convert text file to XML

I have a .txt file and i want to convert it into .xml file using c#. The txt file looks like

a/b/c
a/b
a/b/c/d
e

OUTPUT:

<root>
<a>
  <b>
     <c>
       <d></d>
     </c>
   </b>
<a>
<a>
  <b>
     <c></c>
 </b>
</a>
<a>
  <b></b>
</a>
<e>
</root>

Can you instruct?!

I think the easiest way to solve this is a recursive approach

method:

public static string GetXML(IEnumerable<string> Items)
{
    if (Items.Any())
    {
        return string.Format("<{0}>{1}</{0}>", Items.First(), GetXML(Items.Skip(1)));
    }
    else
    {
        return string.Empty;
    }
}

call:

StringBuilder sbResult = new StringBuilder("<root>");
foreach (string Line in File.ReadAllLines(@"d:\sample.txt"))
{
    sbResult.Append(GetXML(Line.Split('/')));
}
sbResult.Append("</root>");

Ignoring the ordering issues I highlighted in the comments above, here's a one liner (for fun):

XDocument doc = new XDocument(
    new XElement("root",
                 Regex
                  .Split(input, @"\r?\n")
                  .Select(line => line.Split('/')
                                   .Reverse()
                                   .Aggregate((XElement)null,
                                              (prev,curr) => 
                                                  new XElement(curr, prev)))));

Then... How can I save the XML contents of an XDocument as an .xml file?

If next character after a letter is a slash then add the character after the slash inside of the current tag. Otherwhise close the current tag.

You should learn arrays and indexing.

Loading the entire text file into a string array (one line = one string in the array) is possible with the File.ReadAllLines method.

I'll just ignore the fact that the order of your XML file does not follow the order of your txt file. T write a parser for your file, you have to split your String by new line symbols (Environment.NewLine or "\\n") and by "/" and then put the letters on a stack and write them to your with the required encapsulation one at a time.

Put a while loop around the resulting array and set it to the length of your array you have created with the new line splits. Create another loop for each line to split the symbols and put them on a stack.

While putting a symbol on the stack, write it to the file with "<" + symbol + ">". After you have put every symbol of the stack, you just need to pop them and write the symbol to the file ""

Split: C# Split A String By Another String

Maybe I'll write some code when I have time for it, but this should give you a general idea.

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