18910140161

C#编程 Html table 解析器的实现

顺晟科技

2022-09-15 22:31:03

109

html中的表格一般都存储着比较重要的信息,虽然现在css+div已是主流,但笔者还是不建议把信息添加到div中,过度的使用div标签一样是一场灾难^_^。下面的代码可以解析html table,感兴趣的朋友可以看看。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 usingSystem; usingSystem.Collections.Generic; usingSystem.Xml; usingSystem.Text; usingSgml; usingSystem.IO; usingSystem.Netpdf; usingSystem.ComponentModel;    namespaceFreemouse.Base.parser {     /// <summary>     /// html table 解析器     /// </summary>     publicclassHTMLTableReaderpdf : IDisposable     {         privateList<HTMLTable> table;         privateXmlDocument doc;         privateEncoding objEncoding;         privateSgmlReader reader;         privatebyte[] htmlBytes;            privatebooldisposed = false;         privateComponent component = newComponent();            /// <summary>         /// 文本的编码格式        /// </summary>         publicEncoding Encode         {             get{ returnobjEncoding; }             set{ objEncoding = value; }         }         /// <summary>         /// 文档中的表格 pdfv        /// </summary>         publicList<HTMLTable> Tables         {             get{ returntable; }         }         /// <summary>         /// 提供文档中表格的索引访问pdfv         /// </summary>         /// <param name="index">index</param>         /// <returns>HTMLTable</returns>         publicHTMLTable this[intindex]         {             get{                 try                {                     returntable[index];                 }                 catch(Exception e)                 {                     throwe;                 }             }         }         /// <summary>         /// 提供文档中表格的索引访问         /// </summary>         /// <param name="index">table index</param>         /// <param name="subindex">tr index</param>         /// <returns>HTMLTr</returns>         publicHTMLTr this[intindex, intsubindex]         {             get            {                 try                {                     returntable[index].Rows[subindex];                 }                 catch(Exception e)                 {                     throwe;                 }             }         }         /// <summary>         /// 提供文档中表格的索引访问         /// </summary>         /// <param name="index">table index</param>         /// <param name="subindex">tr index</param>         /// <param name="subindex">td index</param>         /// <returns>HTMLTd</returns>         publicHTMLTd this[intindex, intsubindex, intssubindex]         {             get            {                 try                {                     returntable[index].Rows[subindex].Cells[ssubindex];                 }                 catch(Exception e)                 {                     throwe;                 }             }         }            privateStream outStream;         /// <summary>         /// 提供格式化后的标准html文档流,以供保存         /// </summary>         publicStream OutputStream         {             get{ returnoutStream; }             set{ outStream = value; }         }         /// <summary>         /// 构造函数         /// </summary>         publicHTMLTableReader()         {             doc = newXmlDocument();             table = newList<HTMLTable>();             reader = newSgmlReader();             reader.DocType = "strict";             objEncoding = Encoding.Default;             outStream = newMemoryStream();         }         /// <summary>         /// 析构函数         /// </summary>         ~HTMLTableReader()         {             try            {                 if(reader != null)                 {                     reader.Close();                 }                 if(outStream != null)                 {                     outStream.Close();                 }             }             catch(Exception e)             {                 throwe;             }         }         /// <summary>         /// 释放所有资源         /// </summary>         publicvoidDispose()         {             Dispose(true);             GC.SuppressFinalize(this);         }            privatevoidDispose(booldisposing)         {             if(!this.disposed)             {                 if(disposing)                 {                     component.Dispose();                 }                 disposed = true;                }         }            /// <summary>         /// 从文件或URL中获取加载dom         /// </summary>         /// <param name="filename">文件名或URL</param>         /// <param name="encoding">编码</param>         publicvoidLoad(stringfilename,Encoding encoding)         {             Stream readstream = newMemoryStream();             if(Uri.IsWellFormedUriString(filename, UriKind.Absolute))             {                 using(WebClient web = newWebClient())                 {                     try                    {                         web.Encoding = encoding;                         readstream = web.OpenRead(filename);                         Load(readstream, encoding);                     }                     catch(Exception e)                     {                         throwe;                     }                     finally                    {                         readstream.Close();                         web.Dispose();                     }                 }             }             elseif(File.Exists(filename))             {                 using(FileStream fs = newFileStream(filename, FileMode.Open, FileAccess.Read))                 {                     try                    {                         Load(fs, encoding);                     }                     catch(Exception e)                     {                         throwe;                     }                     finally                    {                         fs.Close();                     }                 }             }             else            {                 thrownewException("试图访问不存在的文件");             }         }         /// <summary>         /// 从流设备中加载dom         /// </summary>         /// <param name="stream">流</param>         /// <param name="encode">编码</param>         publicvoidLoad(Stream stream,Encoding encode)         {             using( StreamWriter output = newStreamWriter(outStream, encode) ){                 using(XmlTextWriter writer = newXmlTextWriter(outStream, encode))                 {                     try                    {                         reader.InputStream = newStreamReader(stream, encode);                         reader.WhitespaceHandling = WhitespaceHandling.None;                         writer.Formatting = Formatting.Indented;                         writer.WriteStartDocument();                         //设置一个根节点                         writer.WriteStartElement("root");                         while(reader.Read())                         {                             //获取html节点                             if(reader.NodeType == XmlNodeType.Element && reader.Name == "html")                             {                                 XmlReader r = reader.ReadSubtree();                             }                             else                            {                                 if(reader.Name == null)                                 {                                     continue;                                 }                                 //写入所有table节点                                 switch(reader.Name.ToLower())                                 {                                     case"table":                                         if(reader.NodeType == XmlNodeType.Element)                                         writer.WriteNode(reader, true);                                         break;                                     case"":                                     default:                                         continue;                                 }                             }                            }                         writer.WriteEndElement();                         writer.WriteEndDocument();                         writer.Flush();                         writer.Close();                         htmlBytes = ((MemoryStream)outStream).GetBuffer();                         //编码转换                         if(objEncoding != encode)                         {                             htmlBytes = Encoding.Convert(encode, objEncoding, htmlBytes, 0, htmlBytes.Length);                         }                         stringxmltext = ReplaceLowOrderASCIICharacters(htmlBytes);                         doc.LoadXml(xmltext);                         getTable();                        }                     catch(Exception e)                     {                         throwe;                     }                     finally                    {                         writer.Close();                         output.Close();                     }                 }             }         }         /// <summary>         /// 从字符串中加载dom         /// </summary>         /// <param name="xmltext">文本</param>         /// <param name="encode">编码</param>         publicvoidLoadXml(stringxmltext,Encoding encode)         {             try            {                 MemoryStream inputStream = newMemoryStream(encode.GetBytes(xmltext));                 Load(inputStream, encode);             }             catch(Exception e)             {                 throwe;             }         }         /// <summary>         /// 查找table         /// </summary>         privatevoidgetTable()         {             XmlNodeList tablelist = doc.GetElementsByTagName("table");             foreach(XmlNode _table intablelist)             {                 table.Add( newHTMLTable( _table));             }         }         /// <summary>         /// 修复xml低位字符串无法解析的问题         /// </summary>         /// <param name="buffer"></param>         /// <returns></returns>         privatestringReplaceLowOrderASCIICharacters(byte[] buffer)         {             stringtmp = objEncoding.GetString(buffer);             StringBuilder info = newStringBuilder();             foreach(charcc intmp)             {                 intss = (int)cc;                 if(((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32)))                     info.AppendFormat(" ", ss);//&#x{0:X};                 elseinfo.Append(cc);             }             returninfo.ToString();         }     }     /// <summary>     /// 代表一个html表格     /// </summary>     publicclassHTMLTable : HTMLTag     {         privateList<HTMLTr> tr;         /// <summary>         /// 代表表格中的行,tr         /// </summary>         publicList<HTMLTr> Rows{             get{ returntr; }         }         /// <summary>         /// 构造函数         /// </summary>         /// <param name="node">xmlnode</param>         publicHTMLTable(XmlNode node) :base(node)         {             tr = newList<HTMLTr>();             getSubElement(node, Tag.tr);             getDeep = false;             foreach(XmlNode snode insubnodelist)             {                 tr.Add(newHTMLTr(snode));             }         }     }     /// <summary>     /// 代表一个table中的行     /// </summary>     publicclassHTMLTr : HTMLTag{            privateList<HTMLTd> td;         /// <summary>         /// 代表行中的单元格,td         /// </summary>         publicList<HTMLTd> Cells{             get{ returntd; }         }         /// <summary>         /// 构造函数         /// </summary>         /// <param name="node">xmlnode</param>         publicHTMLTr(XmlNode node): base(node)         {             td = newList<HTMLTd>();             getSubElement(node, Tag.td);             getDeep = false;             foreach(XmlNode snode insubnodelist)             {                 td.Add(newHTMLTd(snode));             }         }        }     /// <summary>     /// 代表一个table中的单元格     /// </summary>     publicclassHTMLTd : HTMLTag{         publicHTMLTd(XmlNode node):base(node)         {         }     }     /// <summary>     /// 代表一个html标签节点     /// </summary>     publicclassHTMLTag : IDisposable     {         protectedXmlNode node;         protectedboolgetDeep = true;         protectedList<XmlNode> subnodelist;         /// <summary>         /// 标签中的文字         /// </summary>         publicstringValue         {             get            {                 try                {                     returnnode.InnerText;                 }                 catch(Exception)                 {                     return"";                 }             }         }         /// <summary>         /// 标签中的html文本         /// </summary>         publicstringinnerHTML         {             get            {                 try                {                     returnnode.InnerXml;                 }                 catch(Exception)                 {                     return"";                 }             }         }         /// <summary>         /// 属性索引器         /// </summary>         /// <param name="attribute">指定属性名</param>         /// <returns>属性值</returns>         publicstringthis[stringattribute]         {             get            {                 try                {                     returnnode.Attributes[attribute].Value;                 }                 catch(Exception)                 {                     return"";                 }             }         }         /// <summary>         /// 查找指定标签名的子节点         /// </summary>         /// <param name="tagname">标签名</param>         /// <returns>List<HTMLTag></returns>         publicvirtualList<HTMLTag> this[Tag tagname]         {             get            {                 try                {                     getSubElement(node, tagname);                     List<HTMLTag> tags = newList<HTMLTag>();                     foreach(XmlNode _node insubnodelist)                     {                         tags.Add(newHTMLTag(_node));                     }                     returntags;                 }                 catch(Exception)                 {                     returnnewList<HTMLTag>();                 }             }         }         /// <summary>         /// 根据tagname查找元素         /// </summary>         /// <param name="tagname">标签名</param>         /// <returns>List<HTMLTag></returns>         publicvirtualList<HTMLTag> GetElementsByTagName(Tag tagname)         {             returnthis[tagname];         }            privateXmlNode nodecopy;         /// <summary>         /// 根据id查找元素         /// </summary>         /// <param name="id">id</param>         /// <returns>HTMLTag</returns>         publicvirtualHTMLTag GetElementByID(stringid)         {             HTMLTag ht = newHTMLTag(nodecopy);             foreach(XmlNode subnode innodecopy.ChildNodes)             {                 try                {                     stringnodeid = subnode.Attributes["id"].Value;                     {                         if(nodeid.ToLower() == id.ToLower())                         {                             nodecopy = node;                             returnnewHTMLTag(subnode);                         }                         else                        {                             nodecopy = subnode;                             returnGetElementByID(id);                         }                     }                 }                 catch(Exception)                 {                     continue;                 }             }             returnht;         }         /// <summary>         /// 构造函数         /// </summary>         /// <param name="node">节点</param>         publicHTMLTag(XmlNode node)         {             this.node = node;             this.nodecopy = node;             subnodelist = newList<XmlNode>();         }         /// <summary>         /// 查找子结点         /// </summary>         /// <param name="parentnode">父节点</param>         /// <param name="tagname">标签名</param>         protectedvoidgetSubElement(XmlNode parentnode,Tag tagname)         {                foreach(XmlNode subnode inparentnode.ChildNodes)             {                 if(subnode.Name == tagname.ToString())                 {                     subnodelist.Add(subnode);                 }                 if(getDeep && subnode.HasChildNodes)                 {                     getSubElement(subnode,tagname);                 }             }         }            privatebooldisposed = false;         privateComponent component = newComponent();            /// <summary>         /// 释放所有资源         /// </summary>         publicvoidDispose()         {             Dispose(true);             GC.SuppressFinalize(this);         }            privatevoidDispose(booldisposing)         {             if(!this.disposed)             {                 if(disposing)                 {                     component.Dispose();                 }                 disposed = true;                }         }        }     /// <summary>     /// html标签名枚举     /// </summary>     publicenumTag     {             a,             abbr,             acronym,             address,             applet,             area,             b,             Base,             basefont,             bdo,             big,             blockquote,             body,             br,             button,             caption,             center,             cite,             code,             col,             colgroup,             dd,             del,             dfn,             dir,             div,             dl,             dt,             em,             fieldset,             font,             form,             frame,             frameset,             h1,             h2,             h3,             h4,             h5,             h6,             head,             hr,             html,             i,             iframe,             img,             input,             ins,             isindex,             kbd,             label,             legend,             li,             link,             listing,             map,             menu,             meta,             noframes,             noscript,             Object,             ol,             optgroup,             option,             p,             param,             plaintext,             pre,             q,             rb,             rbc,             rp,             rt,             rtc,             ruby,             s,             samp,             script,             select,             small,             span,             strike,             strong,             style,             sub,             sup,             table,             tbody,             td,             textarea,             tfoot,             th,             thead,             title,             tr,             tt,             u,             ul,             var,             xmp,             nextid     }
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航