数据文件
大菜单1:小菜单1,小菜单,小菜单,小菜单
大菜单1:小菜单1,小菜单,小菜单
大菜单1:小菜单1
大菜单1:小菜单1,小菜单,小菜单,小菜单
大菜单1:小菜单1,小菜单,小菜单
大菜单1:小菜单1,小菜单
html文件
<html>
<head>
<title>测试stringbuilder链接html</title>
</head>
<body>
{0}
</body>
</html>
c#代码控制台
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace StringBuilder练习 { class Program { static void Main(string[] args) { //读取数据文件 string[] DataLines = File.ReadAllLines("数据文件.txt", Encoding.Default); //拼接原来的html字符串 string HtmlLine = File.ReadAllText("123.html",Encoding.Default); //拼接字符串 StringBuilder mysb = new StringBuilder(); //拼接小字符串,填坑 StringBuilder mysbpinjie = new StringBuilder(); for (int i = 0; i < DataLines.Length; i++) { //循环一次就把数据加入进去得到了拼接的所有数据 mysbpinjie.Append(GetMenu(DataLines[i])); } //把数据写入到html中 mysb.AppendFormat(HtmlLine,mysbpinjie.ToString()); Console.WriteLine(mysb.ToString()); Console.ReadKey(); } public static string GetMenu(string dataLine) { //获得凭借字符串的对象stringbuilder StringBuilder mysb = new StringBuilder(); // 获得大菜单 string[] Menu = dataLine.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); //获取小菜单 string Temp = Menu[1]; //拼接大菜单项 mysb.AppendFormat("<ul><a href="#">{0}</a>",Menu[0]); //拼接小菜单 string[] SubMenu = Temp.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < SubMenu.Length; i++) { mysb.AppendFormat("<li>{0}</li> ", SubMenu[i]); } //拼接结尾处 mysb.Append("</ul>"); return mysb.ToString(); } } }