C#編程 Html table 解析器的實現

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
using System;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using Sgml;
using System.IO;
using System.Netpdf;
using System.ComponentModel;
  
namespace Freemouse.Base.parser
{
    /// <summary>
    /// html table 解析器
    /// </summary>
    public class HTMLTableReaderpdf : IDisposable
    {
        private List<HTMLTable> table;
        private XmlDocument doc;
        private Encoding objEncoding;
        private SgmlReader reader;
        private byte[] htmlBytes;
  
        private bool disposed = false;
        private Component component = new Component();
  
        /// <summary>
        /// 文本的編碼格式        /// </summary>
        public Encoding Encode
        {
            get { return objEncoding; }
            set { objEncoding = value; }
        }
        /// <summary>
        /// 文檔中的表格 pdfv
        /// </summary>
        public List<HTMLTable> Tables
        {
            get { return table; }
        }
        /// <summary>
        /// 提供文檔中表格的索引訪問pdfv
        /// </summary>
        /// <param name="index">index</param>
        /// <returns>HTMLTable</returns>
        public HTMLTable this[int index]
        {
            get {
                try
                {
                    return table[index];
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
        /// <summary>
        /// 提供文檔中表格的索引訪問
        /// </summary>
        /// <param name="index">table index</param>
        /// <param name="subindex">tr index</param>
        /// <returns>HTMLTr</returns>
        public HTMLTr this[int index, int subindex]
        {
            get
            {
                try
                {
                    return table[index].Rows[subindex];
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
        /// <summary>
        /// 提供文檔中表格的索引訪問
        /// </summary>
        /// <param name="index">table index</param>
        /// <param name="subindex">tr index</param>
        /// <param name="subindex">td index</param>
        /// <returns>HTMLTd</returns>
        public HTMLTd this[int index, int subindex, int ssubindex]
        {
            get
            {
                try
                {
                    return table[index].Rows[subindex].Cells[ssubindex];
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
  
        private Stream outStream;
        /// <summary>
        /// 提供格式化後的標準html文檔流,以供保存
        /// </summary>
        public Stream OutputStream
        {
            get { return outStream; }
            set { outStream = value; }
        }
        /// <summary>
        /// 構造函數
        /// </summary>
        public HTMLTableReader()
        {
            doc = new XmlDocument();
            table = new List<HTMLTable>();
            reader = new SgmlReader();
            reader.DocType = "strict";
            objEncoding = Encoding.Default;
            outStream = new MemoryStream();
        }
        /// <summary>
        /// 析構函數
        /// </summary>
        ~HTMLTableReader()
        {
            try
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (outStream != null)
                {
                    outStream.Close();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 釋放所有資源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
  
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    component.Dispose();
                }
                disposed = true;
  
            }
        }
  
        /// <summary>
        /// 從文件或URL中獲取加載dom
        /// </summary>
        /// <param name="filename">文件名或URL</param>
        /// <param name="encoding">編碼</param>
        public void Load(string filename,Encoding encoding)
        {
            Stream readstream = new MemoryStream();
            if (Uri.IsWellFormedUriString(filename, UriKind.Absolute))
            {
                using (WebClient web = new WebClient())
                {
                    try
                    {
                        web.Encoding = encoding;
                        readstream = web.OpenRead(filename);
                        Load(readstream, encoding);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        readstream.Close();
                        web.Dispose();
                    }
                }
            }
            else if (File.Exists(filename))
            {
                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        Load(fs, encoding);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        fs.Close();
                    }
                }
            }
            else
            {
                throw new Exception("試圖訪問不存在的文件");
            }
        }
        /// <summary>
        /// 從流設備中加載dom
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="encode">編碼</param>
        public void Load(Stream stream,Encoding encode)
        {
            using( StreamWriter output = new StreamWriter(outStream, encode) ){
                using (XmlTextWriter writer = new XmlTextWriter(outStream, encode))
                {
                    try
                    {
                        reader.InputStream = new StreamReader(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);
                        }
                        string xmltext = ReplaceLowOrderASCIICharacters(htmlBytes);
                        doc.LoadXml(xmltext);
                        getTable();
  
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                    finally
                    {
                        writer.Close();
                        output.Close();
                    }
                }
            }
        }
        /// <summary>
        /// 從字符串中加載dom
        /// </summary>
        /// <param name="xmltext">文本</param>
        /// <param name="encode">編碼</param>
        public void LoadXml(string xmltext,Encoding encode)
        {
            try
            {
                MemoryStream inputStream = new MemoryStream(encode.GetBytes(xmltext));
                Load(inputStream, encode);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 查找table
        /// </summary>
        private void getTable()
        {
            XmlNodeList tablelist = doc.GetElementsByTagName("table");
            foreach (XmlNode _table in tablelist)
            {
                table.Add( new HTMLTable( _table));
            }
        }
        /// <summary>
        /// 修復xml低位字符串無法解析的問題
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        private string ReplaceLowOrderASCIICharacters(byte[] buffer)
        {
            string tmp = objEncoding.GetString(buffer);
            StringBuilder info = new StringBuilder();
            foreach (char cc in tmp)
            {
                int ss = (int)cc;
                if (((ss >= 0) && (ss <= 8)) || ((ss >= 11) && (ss <= 12)) || ((ss >= 14) && (ss <= 32)))
                    info.AppendFormat(" ", ss);//&#x{0:X};
                else info.Append(cc);
            }
            return info.ToString();
        }
    }
    /// <summary>
    /// 代表一個html表格
    /// </summary>
    public class HTMLTable : HTMLTag
    {
        private List<HTMLTr> tr;
        /// <summary>
        /// 代表表格中的行,tr
        /// </summary>
        public List<HTMLTr> Rows{
            get{ return tr; }
        }
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="node">xmlnode</param>
        public HTMLTable(XmlNode node) :base(node)
        {
            tr = new List<HTMLTr>();
            getSubElement(node, Tag.tr);
            getDeep = false;
            foreach (XmlNode snode in subnodelist)
            {
                tr.Add(new HTMLTr(snode));
            }
        }
    }
    /// <summary>
    /// 代表一個table中的行
    /// </summary>
    public class HTMLTr : HTMLTag{
  
        private List<HTMLTd> td;
        /// <summary>
        /// 代表行中的單元格,td
        /// </summary>
        public List<HTMLTd> Cells{
            get{ return td; }
        }
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="node">xmlnode</param>
        public HTMLTr(XmlNode node): base(node)
        {
            td = new List<HTMLTd>();
            getSubElement(node, Tag.td);
            getDeep = false;
            foreach (XmlNode snode in subnodelist)
            {
                td.Add(new HTMLTd(snode));
            }
        }
  
    }
    /// <summary>
    /// 代表一個table中的單元格
    /// </summary>
    public class HTMLTd : HTMLTag{
        public HTMLTd(XmlNode node):base(node)
        {
        }
    }
    /// <summary>
    /// 代表一個html標籤節點
    /// </summary>
    public class HTMLTag : IDisposable
    {
        protected XmlNode node;
        protected bool getDeep = true;
        protected List<XmlNode> subnodelist;
        /// <summary>
        /// 標籤中的文字
        /// </summary>
        public string Value
        {
            get
            {
                try
                {
                    return node.InnerText;
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }
        /// <summary>
        /// 標籤中的html文本
        /// </summary>
        public string innerHTML
        {
            get
            {
                try
                {
                    return node.InnerXml;
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }
        /// <summary>
        /// 屬性索引器
        /// </summary>
        /// <param name="attribute">指定屬性名</param>
        /// <returns>屬性值</returns>
        public string this[string attribute]
        {
            get
            {
                try
                {
                    return node.Attributes[attribute].Value;
                }
                catch (Exception)
                {
                    return "";
                }
            }
        }
        /// <summary>
        /// 查找指定標籤名的子節點
        /// </summary>
        /// <param name="tagname">標籤名</param>
        /// <returns>List<HTMLTag></returns>
        public virtual List<HTMLTag> this[Tag tagname]
        {
            get
            {
                try
                {
                    getSubElement(node, tagname);
                    List<HTMLTag> tags = new List<HTMLTag>();
                    foreach (XmlNode _node in subnodelist)
                    {
                        tags.Add(new HTMLTag(_node));
                    }
                    return tags;
                }
                catch (Exception)
                {
                    return new List<HTMLTag>();
                }
            }
        }
        /// <summary>
        /// 根據tagname查找元素
        /// </summary>
        /// <param name="tagname">標籤名</param>
        /// <returns>List<HTMLTag></returns>
        public virtual List<HTMLTag> GetElementsByTagName(Tag tagname)
        {
            return this[tagname];
        }
  
        private XmlNode nodecopy;
        /// <summary>
        /// 根據id查找元素
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>HTMLTag</returns>
        public virtual HTMLTag GetElementByID(string id)
        {
            HTMLTag ht = new HTMLTag(nodecopy);
            foreach (XmlNode subnode in nodecopy.ChildNodes)
            {
                try
                {
                    string nodeid = subnode.Attributes["id"].Value;
                    {
                        if (nodeid.ToLower() == id.ToLower())
                        {
                            nodecopy = node;
                            return new HTMLTag(subnode);
                        }
                        else
                        {
                            nodecopy = subnode;
                            return GetElementByID(id);
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            return ht;
        }
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="node">節點</param>
        public HTMLTag(XmlNode node)
        {
            this.node = node;
            this.nodecopy = node;
            subnodelist = new List<XmlNode>();
        }
        /// <summary>
        /// 查找子結點
        /// </summary>
        /// <param name="parentnode">父節點</param>
        /// <param name="tagname">標籤名</param>
        protected void getSubElement(XmlNode parentnode,Tag tagname)
        {
  
            foreach (XmlNode subnode in parentnode.ChildNodes)
            {
                if (subnode.Name == tagname.ToString())
                {
                    subnodelist.Add(subnode);
                }
                if(getDeep && subnode.HasChildNodes)
                {
                    getSubElement(subnode,tagname);
                }
            }
        }
  
        private bool disposed = false;
        private Component component = new Component();
  
        /// <summary>
        /// 釋放所有資源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
  
        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    component.Dispose();
                }
                disposed = true;
  
            }
        }
  
    }
    /// <summary>
    /// html標籤名枚舉
    /// </summary>
    public enum Tag
    {
            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
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章