当前位置:首页 > Windows程序 > 正文

C#对HTML文档的解析

2021-03-27 Windows程序

static void Main(string[] args) { string strWebContent = @"<table><thead> <tr> <th>时间</th> <th>类型</th> <th>名称</th> <th>单位</th> <th>金额</th> </tr> </thead> <tbody>" + @"<tr> <td>2013-12-29</td> <td>发票1</td> <td>采购物资发票1</td> <td>某某公司1</td> <td>123元</td> </tr>" + @"<tr> <td>2013-12-29</td> <td>发票2</td> <td>采购物资发票2</td> <td>某某公司2</td> <td>321元</td> </tr> </tbody> </table> "; List<Data> datas = new List<Data>();//定义1个列表用于保存结果 HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(strWebContent);//加载HTML字符串,如果是文件可以用htmlDocument.Load方法加载 HtmlNodeCollection collection = htmlDocument.DocumentNode.SelectSingleNode("table/tbody").ChildNodes;//跟Xpath一样,轻松的定位到相应节点下 foreach (HtmlNode node in collection) { //去除\r\n以及空格,获取到相应td里面的数据 string[] line = node.InnerText.Split(new char[] { \r, \n, }, StringSplitOptions.RemoveEmptyEntries); //如果符合条件,就加载到对象列表里面 if (line.Length == 5) datas.Add(new Data() { 时间 = line[0], 类型 = line[1], 名称 = line[2], 单位 = line[3], 金额 = line[4] }); } //循环输出查看结果是否正确 foreach (var v in datas) { Console.WriteLine(string.Join(",", v.时间, v.类型, v.名称, v.单位, v.金额)); } }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68590.html