I have this: Example input:
* First item
* Second item
* Subitem 1
* sub-subitem!
* Subitem 3
* Third item
Example output:
<ul>
<li>First item</li>
<li>Second item
<ul>
<li>Subitem 1
<ul>
<li>sub-subitem!</li>
</ul>
</li>
<li>Subitem 3</li>
</ul>
</li>
<li>Third item</li>
</ul>
I have created a Java class that send every String line to an array of chars and I treat every character alone. My problem is when to close the tags Any idea?
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextToHtml {
StringBuilder itemName = new StringBuilder();
String sCurrentLine;
int usingUlTAG=0;
public TextToHtml(){
BufferedReader br = null;
try {
boolean closeLItag=false;
br = new BufferedReader(new FileReader("NestedText.txt"));
System.out.println("<ul>");
while ((sCurrentLine = br.readLine()) != null) {
char[] item = sCurrentLine.toCharArray();
for(int i=0; i<item.length;i++){
if(item[i]!='*' && item[i]!='\n' && item[i]!='\t'){
itemName.append(item[i]);
continue;
}
if(item[i]=='*'){
itemName.append("<li>");
closeLItag=true;
}
else if(item[i]=='\t'){
if(item[i+1]=='*'){
if(usingUlTAG<1)
itemName.append("\t<ul>\n\t\t");
itemName.append("\t\n\t\t");
usingUlTAG= 1;
continue;
}
if(item[i+1]=='\t'){
itemName.append("\t\t<ul>\n\n\t\t");
usingUlTAG=2;
continue;
}
}
}
if(closeLItag){
itemName.append("</li>\n");
}
}
System.out.println(itemName+"/ul>");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new TextToHtml();
}
}
You'll have to look ahead to the next line and see if its list level is different from the current item's. Then you can add or close tags based on the difference in level, if any. Here's code that does this:
Note that this will only work if the levels are indented with tabs, not spaces.