-
-
Notifications
You must be signed in to change notification settings - Fork 381
/
HtmlDocument.cs
2296 lines (1956 loc) · 80.8 KB
/
HtmlDocument.cs
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators.
// Website & Documentation: https://html-agility-pack.net
// Forum & Issues: https://github.com/zzzprojects/html-agility-pack
// License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE
// More projects: https://zzzprojects.com/
// Copyright © ZZZ Projects Inc. All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace HtmlAgilityPack
{
/// <summary>
/// Represents a complete HTML document.
/// </summary>
public partial class HtmlDocument
{
#region Manager
internal static bool _disableBehaviorTagP = true;
/// <summary>True to disable, false to enable the behavior tag p.</summary>
public static bool DisableBehaviorTagP
{
get => _disableBehaviorTagP;
set
{
if (value)
{
if (HtmlNode.ElementsFlags.ContainsKey("p"))
{
HtmlNode.ElementsFlags.Remove("p");
}
}
else
{
if (!HtmlNode.ElementsFlags.ContainsKey("p"))
{
HtmlNode.ElementsFlags.Add("p", HtmlElementFlag.Empty | HtmlElementFlag.Closed);
}
}
_disableBehaviorTagP = value;
}
}
/// <summary>Default builder to use in the HtmlDocument constructor</summary>
public static Action<HtmlDocument> DefaultBuilder { get; set; }
/// <summary>Action to execute before the Parse is executed</summary>
public Action<HtmlDocument> ParseExecuting { get; set; }
#endregion
#region Fields
/// <summary>
/// Defines the max level we would go deep into the html document
/// </summary>
private static int _maxDepthLevel = int.MaxValue;
private int _c;
private Crc32 _crc32;
private HtmlAttribute _currentattribute;
private HtmlNode _currentnode;
private Encoding _declaredencoding;
private HtmlNode _documentnode;
private bool _fullcomment;
private int _index;
internal Dictionary<string, HtmlNode> Lastnodes = new Dictionary<string, HtmlNode>();
private HtmlNode _lastparentnode;
private int _line;
private int _lineposition, _maxlineposition;
internal Dictionary<string, HtmlNode> Nodesid;
private ParseState _oldstate;
private bool _onlyDetectEncoding;
internal Dictionary<int, HtmlNode> Openednodes;
private List<HtmlParseError> _parseerrors = new List<HtmlParseError>();
private string _remainder;
private int _remainderOffset;
private ParseState _state;
private Encoding _streamencoding;
private bool _useHtmlEncodingForStream;
/// <summary>The HtmlDocument Text. Careful if you modify it.</summary>
public string Text;
/// <summary>True to stay backward compatible with previous version of HAP. This option does not guarantee 100% compatibility.</summary>
public bool BackwardCompatibility = true;
/// <summary>
/// Adds Debugging attributes to node. Default is false.
/// </summary>
public bool OptionAddDebuggingAttributes;
/// <summary>
/// Defines if closing for non closed nodes must be done at the end or directly in the document.
/// Setting this to true can actually change how browsers render the page. Default is false.
/// </summary>
public bool OptionAutoCloseOnEnd; // close errors at the end
/// <summary>
/// Defines if non closed nodes will be checked at the end of parsing. Default is true.
/// </summary>
public bool OptionCheckSyntax = true;
/// <summary>
/// Defines if a checksum must be computed for the document while parsing. Default is false.
/// </summary>
public bool OptionComputeChecksum;
/// <summary>
/// Defines if SelectNodes method will return null or empty collection when no node matched the XPath expression.
/// Setting this to true will return empty collection and false will return null. Default is false.
/// </summary>
public bool OptionEmptyCollection = false;
/// <summary>True of the whole <![CDATA[ block should be treated as a single comment.</summary>
public bool OptionTreatCDataBlockAsComment;
/// <summary>True to disable, false to enable the server side code.</summary>
public bool DisableServerSideCode = false;
/// <summary>
/// Defines the default stream encoding to use. Default is System.Text.Encoding.Default.
/// </summary>
public Encoding OptionDefaultStreamEncoding;
/// <summary>
/// Force to take the original comment instead of creating it
/// </summary>
public bool OptionXmlForceOriginalComment;
/// <summary>
/// Defines if source text must be extracted while parsing errors.
/// If the document has a lot of errors, or cascading errors, parsing performance can be dramatically affected if set to true.
/// Default is false.
/// </summary>
public bool OptionExtractErrorSourceText;
// turning this on can dramatically slow performance if a lot of errors are detected
/// <summary>
/// Defines the maximum length of source text or parse errors. Default is 100.
/// </summary>
public int OptionExtractErrorSourceTextMaxLength = 100;
/// <summary>
/// Defines if LI, TR, TH, TD tags must be partially fixed when nesting errors are detected. Default is false.
/// </summary>
public bool OptionFixNestedTags; // fix li, tr, th, td tags
/// <summary>
/// Defines if output must conform to XML, instead of HTML. Default is false.
/// </summary>
public bool OptionOutputAsXml;
/// <summary>True to disable implicit end. An explicit end logic will be used instead.</summary>
public bool DisableImplicitEnd;
/// <summary>
/// If used together with <see cref="OptionOutputAsXml"/> and enabled, Xml namespaces in element names are preserved. Default is false.
/// </summary>
public bool OptionPreserveXmlNamespaces;
/// <summary>
/// Defines if attribute value output must be optimized (not bound with double quotes if it is possible). Default is false.
/// </summary>
public bool OptionOutputOptimizeAttributeValues;
/// <summary>Defines the global attribute value quote. When specified, it will always win.</summary>
public AttributeValueQuote? GlobalAttributeValueQuote;
/// <summary>
/// Defines if name must be output with it's original case. Useful for asp.net tags and attributes. Default is false.
/// </summary>
public bool OptionOutputOriginalCase;
/// <summary>
/// Defines if name must be output in uppercase. Default is false.
/// </summary>
public bool OptionOutputUpperCase;
/// <summary>
/// Defines if declared encoding must be read from the document.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node.
/// Default is true.
/// </summary>
public bool OptionReadEncoding = true;
/// <summary>
/// Defines the name of a node that will throw the StopperNodeException when found as an end node. Default is null.
/// </summary>
public string OptionStopperNodeName;
/// <summary>
/// Defines if attributes should use original names by default, rather than lower case. Default is false.
/// </summary>
public bool OptionDefaultUseOriginalName;
/// <summary>
/// Defines if the 'id' attribute must be specifically used. Default is true.
/// </summary>
public bool OptionUseIdAttribute = true;
/// <summary>
/// Defines if empty nodes must be written as closed during output. Default is false.
/// </summary>
public bool OptionWriteEmptyNodes;
/// <summary>
/// Defines if empty nodes must be written without the additional space. Default is false.
/// </summary>
public bool OptionWriteEmptyNodesWithoutSpace;
/// <summary>
/// The max number of nested child nodes.
/// Added to prevent stackoverflow problem when a page has tens of thousands of opening html tags with no closing tags
/// </summary>
public int OptionMaxNestedChildNodes = 0;
/// <summary>
/// Enable to create a "new line" for tag such as "br"
/// </summary>
public bool OptionEnableBreakLineForInnerText;
#endregion
#region Static Members
internal static readonly string HtmlExceptionRefNotChild = "Reference node must be a child of this node";
internal static readonly string HtmlExceptionUseIdAttributeFalse = "You need to set UseIdAttribute property to true to enable this feature";
internal static readonly string HtmlExceptionClassDoesNotExist = "Class name doesn't exist";
internal static readonly string HtmlExceptionClassExists = "Class name already exists";
internal static readonly Dictionary<string, string[]> HtmlResetters = new Dictionary<string, string[]>()
{
{"li", new[] {"ul", "ol"}},
{"tr", new[] {"table"}},
{"th", new[] {"tr", "table"}},
{"td", new[] {"tr", "table"}},
};
#endregion
#region Constructors
/// <summary>
/// Creates an instance of an HTML document.
/// </summary>
public HtmlDocument()
{
if (DefaultBuilder != null)
{
DefaultBuilder(this);
}
_documentnode = CreateNode(HtmlNodeType.Document, 0);
#if SILVERLIGHT || METRO || NETSTANDARD1_3 || NETSTANDARD1_6
OptionDefaultStreamEncoding = Encoding.UTF8;
#else
OptionDefaultStreamEncoding = Encoding.Default;
#endif
}
#endregion
#region Properties
/// <summary>Gets the parsed text.</summary>
/// <value>The parsed text.</value>
public string ParsedText
{
get { return Text; }
}
/// <summary>
/// Defines the max level we would go deep into the html document. If this depth level is exceeded, and exception is
/// thrown.
/// </summary>
public static int MaxDepthLevel
{
get { return _maxDepthLevel; }
set { _maxDepthLevel = value; }
}
/// <summary>
/// Gets the document CRC32 checksum if OptionComputeChecksum was set to true before parsing, 0 otherwise.
/// </summary>
public int CheckSum
{
get { return _crc32 == null ? 0 : (int) _crc32.CheckSum; }
}
/// <summary>
/// Gets the document's declared encoding.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node (pre-HTML5) or the meta charset="XXXXX" html node (HTML5).
/// </summary>
public Encoding DeclaredEncoding
{
get { return _declaredencoding; }
}
/// <summary>
/// Gets the root node of the document.
/// </summary>
public HtmlNode DocumentNode
{
get { return _documentnode; }
}
/// <summary>
/// Gets the document's output encoding.
/// </summary>
public Encoding Encoding
{
get { return GetOutEncoding(); }
}
/// <summary>
/// Gets a list of parse errors found in the document.
/// </summary>
public IEnumerable<HtmlParseError> ParseErrors
{
get { return _parseerrors; }
}
/// <summary>
/// Gets the remaining text.
/// Will always be null if OptionStopperNodeName is null.
/// </summary>
public string Remainder
{
get { return _remainder; }
}
/// <summary>
/// Gets the offset of Remainder in the original Html text.
/// If OptionStopperNodeName is null, this will return the length of the original Html text.
/// </summary>
public int RemainderOffset
{
get { return _remainderOffset; }
}
/// <summary>
/// Gets the document's stream encoding.
/// </summary>
public Encoding StreamEncoding
{
get { return _streamencoding; }
}
#endregion
#region Public Methods
/// <summary>
/// Gets a valid XML name.
/// </summary>
/// <param name="name">Any text.</param>
/// <returns>A string that is a valid XML name.</returns>
public static string GetXmlName(string name)
{
return GetXmlName(name, false, false);
}
#if !METRO
public void UseAttributeOriginalName(string tagName)
{
foreach (var nod in this.DocumentNode.SelectNodes("//" + tagName))
{
foreach (var attribut in nod.Attributes)
{
attribut.UseOriginalName = true;
}
}
}
#endif
public static string GetXmlName(string name, bool isAttribute, bool preserveXmlNamespaces)
{
string xmlname = string.Empty;
bool nameisok = true;
for (int i = 0; i < name.Length; i++)
{
// names are lcase
// note: we are very limited here, too much?
if (((name[i] >= 'a') && (name[i] <= 'z')) ||
((name[i] >= 'A') && (name[i] <= 'Z')) ||
((name[i] >= '0') && (name[i] <= '9')) ||
((isAttribute || preserveXmlNamespaces) && name[i] == ':') ||
// (name[i]==':') || (name[i]=='_') || (name[i]=='-') || (name[i]=='.')) // these are bads in fact
(name[i] == '_') || (name[i] == '-') || (name[i] == '.'))
{
xmlname += name[i];
}
else
{
nameisok = false;
byte[] bytes = Encoding.UTF8.GetBytes(new char[] {name[i]});
for (int j = 0; j < bytes.Length; j++)
{
xmlname += bytes[j].ToString("x2");
}
xmlname += "_";
}
}
if (nameisok)
{
return xmlname;
}
return "_" + xmlname;
}
/// <summary>
/// Applies HTML encoding to a specified string.
/// </summary>
/// <param name="html">The input string to encode. May not be null.</param>
/// <returns>The encoded string.</returns>
public static string HtmlEncode(string html)
{
return HtmlEncodeWithCompatibility(html, true);
}
internal static string HtmlEncodeWithCompatibility(string html, bool backwardCompatibility = true)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
// replace & by & but only once!
Regex rx = backwardCompatibility ? new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;))", RegexOptions.IgnoreCase) : new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;)|(nbsp;)|(reg;))", RegexOptions.IgnoreCase);
return rx.Replace(html, "&").Replace("<", "<").Replace(">", ">").Replace("\"", """);
}
/// <summary>
/// Determines if the specified character is considered as a whitespace character.
/// </summary>
/// <param name="c">The character to check.</param>
/// <returns>true if if the specified character is considered as a whitespace character.</returns>
public static bool IsWhiteSpace(int c)
{
if ((c == 10) || (c == 13) || (c == 32) || (c == 9))
{
return true;
}
return false;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name)
{
if (name == null)
throw new ArgumentNullException("name");
HtmlAttribute att = CreateAttribute();
att.Name = name;
return att;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <param name="value">The value of the attribute.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlAttribute att = CreateAttribute(name);
att.Value = value;
return att;
}
/// <summary>
/// Creates an HTML comment node.
/// </summary>
/// <returns>The new HTML comment node.</returns>
public HtmlCommentNode CreateComment()
{
return (HtmlCommentNode) CreateNode(HtmlNodeType.Comment);
}
/// <summary>
/// Creates an HTML comment node with the specified comment text.
/// </summary>
/// <param name="comment">The comment text. May not be null.</param>
/// <returns>The new HTML comment node.</returns>
public HtmlCommentNode CreateComment(string comment)
{
if (comment == null)
{
throw new ArgumentNullException("comment");
}
if (!comment.StartsWith("<!--") && !comment.EndsWith("-->"))
{
comment = "<!--" + comment + "-->";
}
HtmlCommentNode c = CreateComment();
c.Comment = comment;
return c;
}
/// <summary>
/// Creates an HTML element node with the specified name.
/// </summary>
/// <param name="name">The qualified name of the element. May not be null.</param>
/// <returns>The new HTML node.</returns>
public HtmlNode CreateElement(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlNode node = CreateNode(HtmlNodeType.Element);
node.SetName(name);
return node;
}
/// <summary>
/// Creates an HTML text node.
/// </summary>
/// <returns>The new HTML text node.</returns>
public HtmlTextNode CreateTextNode()
{
return (HtmlTextNode) CreateNode(HtmlNodeType.Text);
}
/// <summary>
/// Creates an HTML text node with the specified text.
/// </summary>
/// <param name="text">The text of the node. May not be null.</param>
/// <returns>The new HTML text node.</returns>
public HtmlTextNode CreateTextNode(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
HtmlTextNode t = CreateTextNode();
t.Text = text;
return t;
}
/// <summary>
/// Detects the encoding of an HTML stream.
/// </summary>
/// <param name="stream">The input stream. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(Stream stream)
{
return DetectEncoding(stream, false);
}
/// <summary>
/// Detects the encoding of an HTML stream.
/// </summary>
/// <param name="stream">The input stream. May not be null.</param>
/// <param name="checkHtml">The html is checked.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(Stream stream, bool checkHtml)
{
_useHtmlEncodingForStream = checkHtml;
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return DetectEncoding(new StreamReader(stream));
}
/// <summary>
/// Detects the encoding of an HTML text provided on a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(TextReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
_onlyDetectEncoding = true;
if (OptionCheckSyntax)
{
Openednodes = new Dictionary<int, HtmlNode>();
}
else
{
Openednodes = null;
}
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNode>(StringComparer.OrdinalIgnoreCase);
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null && !_useHtmlEncodingForStream)
{
Text = sr.ReadToEnd();
_streamencoding = sr.CurrentEncoding;
return _streamencoding;
}
_streamencoding = null;
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = CreateNode(HtmlNodeType.Document, 0);
// this is almost a hack, but it allows us not to muck with the original parsing code
try
{
Parse();
}
catch (EncodingFoundException ex)
{
return ex.Encoding;
}
return _streamencoding;
}
/// <summary>
/// Detects the encoding of an HTML text.
/// </summary>
/// <param name="html">The input html text. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncodingHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using (StringReader sr = new StringReader(html))
{
Encoding encoding = DetectEncoding(sr);
return encoding;
}
}
/// <summary>
/// Gets the HTML node with the specified 'id' attribute value.
/// </summary>
/// <param name="id">The attribute id to match. May not be null.</param>
/// <returns>The HTML node with the matching id or null if not found.</returns>
public HtmlNode GetElementbyId(string id)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (Nodesid == null)
{
throw new Exception(HtmlExceptionUseIdAttributeFalse);
}
return Nodesid.ContainsKey(id) ? Nodesid[id] : null;
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public void Load(Stream stream)
{
Load(new StreamReader(stream, OptionDefaultStreamEncoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public void Load(Stream stream, Encoding encoding)
{
Load(new StreamReader(stream, encoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize));
}
/// <summary>
/// Loads the HTML document from the specified TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document. May not be null.</param>
public void Load(TextReader reader)
{
// all Load methods pass down to this one
if (reader == null)
throw new ArgumentNullException("reader");
_onlyDetectEncoding = false;
if (OptionCheckSyntax)
Openednodes = new Dictionary<int, HtmlNode>();
else
Openednodes = null;
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNode>(StringComparer.OrdinalIgnoreCase);
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null)
{
try
{
// trigger bom read if needed
sr.Peek();
}
// ReSharper disable EmptyGeneralCatchClause
catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
{
// void on purpose
}
_streamencoding = sr.CurrentEncoding;
}
else
{
_streamencoding = null;
}
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = CreateNode(HtmlNodeType.Document, 0);
Parse();
if (!OptionCheckSyntax || Openednodes == null) return;
foreach (HtmlNode node in Openednodes.Values)
{
if (!node._starttag) // already reported
{
continue;
}
string html;
if (OptionExtractErrorSourceText)
{
html = node.OuterHtml;
if (html.Length > OptionExtractErrorSourceTextMaxLength)
{
html = html.Substring(0, OptionExtractErrorSourceTextMaxLength);
}
}
else
{
html = string.Empty;
}
AddError(
HtmlParseErrorCode.TagNotClosed,
node._line, node._lineposition,
node._streamposition, html,
"End tag </" + node.Name + "> was not found");
}
// we don't need this anymore
Openednodes.Clear();
}
/// <summary>
/// Loads the HTML document from the specified string.
/// </summary>
/// <param name="html">String containing the HTML document to load. May not be null.</param>
public void LoadHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using (StringReader sr = new StringReader(html))
{
Load(sr);
}
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save.</param>
public void Save(Stream outStream)
{
StreamWriter sw = new StreamWriter(outStream, GetOutEncoding());
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save. May not be null.</param>
/// <param name="encoding">The character encoding to use. May not be null.</param>
public void Save(Stream outStream, Encoding encoding)
{
if (outStream == null)
{
throw new ArgumentNullException("outStream");
}
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
StreamWriter sw = new StreamWriter(outStream, encoding);
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified StreamWriter.
/// </summary>
/// <param name="writer">The StreamWriter to which you want to save.</param>
public void Save(StreamWriter writer)
{
Save((TextWriter) writer);
}
/// <summary>
/// Saves the HTML document to the specified TextWriter.
/// </summary>
/// <param name="writer">The TextWriter to which you want to save. May not be null.</param>
public void Save(TextWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
DocumentNode.WriteTo(writer);
writer.Flush();
}
/// <summary>
/// Saves the HTML document to the specified XmlWriter.
/// </summary>
/// <param name="writer">The XmlWriter to which you want to save.</param>
public void Save(XmlWriter writer)
{
DocumentNode.WriteTo(writer);
writer.Flush();
}
#endregion
#region Internal Methods
internal HtmlAttribute CreateAttribute()
{
return new HtmlAttribute(this);
}
internal HtmlNode CreateNode(HtmlNodeType type)
{
return CreateNode(type, -1);
}
internal HtmlNode CreateNode(HtmlNodeType type, int index)
{
switch (type)
{
case HtmlNodeType.Comment:
return new HtmlCommentNode(this, index);
case HtmlNodeType.Text:
return new HtmlTextNode(this, index);
default:
return new HtmlNode(type, this, index);
}
}
internal Encoding GetOutEncoding()
{
// when unspecified, use the stream encoding first
return _declaredencoding ?? (_streamencoding ?? OptionDefaultStreamEncoding);
}
internal HtmlNode GetXmlDeclaration()
{
if (!_documentnode.HasChildNodes)
return null;
foreach (HtmlNode node in _documentnode._childnodes)
if (node.Name == "?xml") // it's ok, names are case sensitive
return node;
return null;
}
internal void SetIdForNode(HtmlNode node, string id)
{
if (!OptionUseIdAttribute)
return;
if ((Nodesid == null) || (id == null))
return;
if (node == null)
Nodesid.Remove(id);
else
Nodesid[id] = node;
}
internal void UpdateLastParentNode()
{
do
{
if (_lastparentnode.Closed)
_lastparentnode = _lastparentnode.ParentNode;
} while ((_lastparentnode != null) && (_lastparentnode.Closed));
if (_lastparentnode == null)
_lastparentnode = _documentnode;
}
#endregion
#region Private Methods
private void AddError(HtmlParseErrorCode code, int line, int linePosition, int streamPosition, string sourceText, string reason)