/
XmlWriterSettings.cs
708 lines (643 loc) · 24.6 KB
/
XmlWriterSettings.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Xml.Xsl.Runtime;
namespace System.Xml
{
public enum XmlOutputMethod
{
Xml = 0, // Use Xml 1.0 rules to serialize
Html = 1, // Use Html rules specified by Xslt specification to serialize
Text = 2, // Only serialize text blocks
AutoDetect = 3, // Choose between Xml and Html output methods at runtime (using Xslt rules to do so)
}
/// <summary>
/// Three-state logic enumeration.
/// </summary>
internal enum TriState
{
Unknown = -1,
False = 0,
True = 1,
};
internal enum XmlStandalone
{
// Do not change the constants - XmlBinaryWriter depends in it
Omit = 0,
Yes = 1,
No = 2,
}
// XmlWriterSettings class specifies basic features of an XmlWriter.
public sealed class XmlWriterSettings
{
internal static readonly XmlWriterSettings s_defaultWriterSettings = new() { ReadOnly = true };
private bool _useAsync;
private Encoding _encoding;
private bool _omitXmlDecl;
private NewLineHandling _newLineHandling;
private string _newLineChars;
private string _indentChars;
private bool _newLineOnAttributes;
private bool _closeOutput;
private NamespaceHandling _namespaceHandling;
private ConformanceLevel _conformanceLevel;
private bool _checkCharacters;
private bool _writeEndDocumentOnClose;
private bool _doNotEscapeUriAttributes;
private bool _mergeCDataSections;
private string? _mediaType;
private string? _docTypeSystem;
private string? _docTypePublic;
private XmlStandalone _standalone;
private bool _autoXmlDecl;
public XmlWriterSettings()
{
Initialize();
}
public bool Async
{
get => _useAsync;
set
{
CheckReadOnly();
_useAsync = value;
}
}
public Encoding Encoding
{
get => _encoding;
[MemberNotNull(nameof(_encoding))]
set
{
CheckReadOnly();
_encoding = value;
}
}
// True if an xml declaration should *not* be written.
public bool OmitXmlDeclaration
{
get => _omitXmlDecl;
set
{
CheckReadOnly();
_omitXmlDecl = value;
}
}
// See NewLineHandling enum for details.
public NewLineHandling NewLineHandling
{
get => _newLineHandling;
set
{
CheckReadOnly();
if (unchecked((uint)value) > (uint)NewLineHandling.None)
{
ThrowArgumentOutOfRangeException(nameof(value));
}
_newLineHandling = value;
}
}
// Line terminator string. By default, this is a carriage return followed by a line feed ("\r\n").
public string NewLineChars
{
get => _newLineChars;
[MemberNotNull(nameof(_newLineChars))]
set
{
CheckReadOnly();
ArgumentNullException.ThrowIfNull(value);
_newLineChars = value;
}
}
// True if output should be indented using rules that are appropriate to the output rules (i.e. Xml, Html, etc).
public bool Indent
{
get => IndentInternal == TriState.True;
set
{
CheckReadOnly();
IndentInternal = value ? TriState.True : TriState.False;
}
}
// Characters to use when indenting. This is usually tab or some spaces, but can be anything.
public string IndentChars
{
get => _indentChars;
[MemberNotNull(nameof(_indentChars))]
set
{
CheckReadOnly();
ArgumentNullException.ThrowIfNull(value);
_indentChars = value;
}
}
// Whether or not indent attributes on new lines.
public bool NewLineOnAttributes
{
get => _newLineOnAttributes;
set
{
CheckReadOnly();
_newLineOnAttributes = value;
}
}
// Whether or not the XmlWriter should close the underlying stream or TextWriter when Close is called on the XmlWriter.
public bool CloseOutput
{
get => _closeOutput;
set
{
CheckReadOnly();
_closeOutput = value;
}
}
// Conformance
// See ConformanceLevel enum for details.
public ConformanceLevel ConformanceLevel
{
get => _conformanceLevel;
set
{
CheckReadOnly();
if (unchecked((uint)value) > (uint)ConformanceLevel.Document)
{
ThrowArgumentOutOfRangeException(nameof(value));
}
_conformanceLevel = value;
}
}
// Whether or not to check content characters that they are valid XML characters.
public bool CheckCharacters
{
get => _checkCharacters;
set
{
CheckReadOnly();
_checkCharacters = value;
}
}
// Whether or not to remove duplicate namespace declarations
public NamespaceHandling NamespaceHandling
{
get => _namespaceHandling;
set
{
CheckReadOnly();
if (unchecked((uint)value) > (uint)(NamespaceHandling.OmitDuplicates))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_namespaceHandling = value;
}
}
//Whether or not to auto complete end-element when close/dispose
public bool WriteEndDocumentOnClose
{
get => _writeEndDocumentOnClose;
set
{
CheckReadOnly();
_writeEndDocumentOnClose = value;
}
}
// Specifies the method (Html, Xml, etc.) that will be used to serialize the result tree.
public XmlOutputMethod OutputMethod { get; internal set; }
public void Reset()
{
CheckReadOnly();
Initialize();
}
// Deep clone all settings (except read-only, which is always set to false). The original and new objects
// can now be set independently of each other.
public XmlWriterSettings Clone()
{
XmlWriterSettings clonedSettings = (XmlWriterSettings)MemberwiseClone();
// Deep clone shared settings that are not immutable
clonedSettings.CDataSectionElements = new List<XmlQualifiedName>(CDataSectionElements);
clonedSettings.ReadOnly = false;
return clonedSettings;
}
// Set of XmlQualifiedNames that identify any elements that need to have text children wrapped in CData sections.
internal List<XmlQualifiedName> CDataSectionElements { get; private set; } = new();
// Used in Html writer to disable encoding of uri attributes
public bool DoNotEscapeUriAttributes
{
get => _doNotEscapeUriAttributes;
set
{
CheckReadOnly();
_doNotEscapeUriAttributes = value;
}
}
internal bool MergeCDataSections
{
get => _mergeCDataSections;
set
{
CheckReadOnly();
_mergeCDataSections = value;
}
}
// Used in Html writer when writing Meta element. Null denotes the default media type.
internal string? MediaType
{
get => _mediaType;
set
{
CheckReadOnly();
_mediaType = value;
}
}
// System Id in doc-type declaration. Null denotes the absence of the system Id.
internal string? DocTypeSystem
{
get => _docTypeSystem;
set
{
CheckReadOnly();
_docTypeSystem = value;
}
}
// Public Id in doc-type declaration. Null denotes the absence of the public Id.
internal string? DocTypePublic
{
get => _docTypePublic;
set
{
CheckReadOnly();
_docTypePublic = value;
}
}
// Yes for standalone="yes", No for standalone="no", and Omit for no standalone.
internal XmlStandalone Standalone
{
get => _standalone;
set
{
CheckReadOnly();
_standalone = value;
}
}
// True if an xml declaration should automatically be output (no need to call WriteStartDocument)
internal bool AutoXmlDeclaration
{
get => _autoXmlDecl;
set
{
CheckReadOnly();
_autoXmlDecl = value;
}
}
// If TriState.Unknown, then Indent property was not explicitly set. In this case, the AutoDetect output
// method will default to Indent=true for Html and Indent=false for Xml.
internal TriState IndentInternal { get; set; }
private bool IsQuerySpecific => CDataSectionElements.Count != 0 || _docTypePublic != null || _docTypeSystem != null || _standalone == XmlStandalone.Yes;
internal XmlWriter CreateWriter(string outputFileName)
{
ArgumentNullException.ThrowIfNull(outputFileName);
// need to clone the settigns so that we can set CloseOutput to true to make sure the stream gets closed in the end
XmlWriterSettings newSettings = this;
if (!newSettings.CloseOutput)
{
newSettings = newSettings.Clone();
newSettings.CloseOutput = true;
}
FileStream? fs = null;
try
{
// open file stream
fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, _useAsync);
// create writer
return newSettings.CreateWriter(fs);
}
catch
{
fs?.Dispose();
throw;
}
}
internal XmlWriter CreateWriter(Stream output)
{
ArgumentNullException.ThrowIfNull(output);
XmlWriter writer;
// create raw writer
Debug.Assert(Encoding.UTF8.WebName == "utf-8");
if (Encoding.WebName == "utf-8")
{ // Encoding.CodePage is not supported in Silverlight
// create raw UTF-8 writer
switch (OutputMethod)
{
case XmlOutputMethod.Xml:
writer = Indent ? new XmlUtf8RawTextWriterIndent(output, this) : new XmlUtf8RawTextWriter(output, this);
break;
case XmlOutputMethod.Html:
writer = Indent ? new HtmlUtf8RawTextWriterIndent(output, this) : new HtmlUtf8RawTextWriter(output, this);
break;
case XmlOutputMethod.Text:
writer = new TextUtf8RawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Fail("Invalid XmlOutputMethod setting.");
return null!;
}
}
else
{
// Otherwise, create a general-purpose writer than can do any encoding
switch (OutputMethod)
{
case XmlOutputMethod.Xml:
writer = Indent ? new XmlEncodedRawTextWriterIndent(output, this) : new XmlEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.Html:
writer = Indent ? new HtmlEncodedRawTextWriterIndent(output, this) : new HtmlEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.Text:
writer = new TextEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Fail("Invalid XmlOutputMethod setting.");
return null!;
}
}
// Wrap with Xslt/XQuery specific writer if needed;
// XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer.
if (OutputMethod != XmlOutputMethod.AutoDetect)
{
if (IsQuerySpecific)
{
// Create QueryOutputWriter if CData sections or DocType need to be tracked
writer = new QueryOutputWriter((XmlRawWriter)writer, this);
}
}
// wrap with well-formed writer
writer = new XmlWellFormedWriter(writer, this);
if (_useAsync)
{
writer = new XmlAsyncCheckWriter(writer);
}
return writer;
}
internal XmlWriter CreateWriter(TextWriter output)
{
ArgumentNullException.ThrowIfNull(output);
XmlWriter writer;
// create raw writer
switch (OutputMethod)
{
case XmlOutputMethod.Xml:
writer = Indent ? new XmlEncodedRawTextWriterIndent(output, this) : new XmlEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.Html:
writer = Indent ? new HtmlEncodedRawTextWriterIndent(output, this) : new HtmlEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.Text:
writer = new TextEncodedRawTextWriter(output, this);
break;
case XmlOutputMethod.AutoDetect:
writer = new XmlAutoDetectWriter(output, this);
break;
default:
Debug.Fail("Invalid XmlOutputMethod setting.");
return null!;
}
// XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer.
if (OutputMethod != XmlOutputMethod.AutoDetect)
{
if (IsQuerySpecific)
{
// Create QueryOutputWriter if CData sections or DocType need to be tracked
writer = new QueryOutputWriter((XmlRawWriter)writer, this);
}
}
// wrap with well-formed writer
writer = new XmlWellFormedWriter(writer, this);
if (_useAsync)
{
writer = new XmlAsyncCheckWriter(writer);
}
return writer;
}
internal XmlWriter CreateWriter(XmlWriter output)
{
ArgumentNullException.ThrowIfNull(output);
return AddConformanceWrapper(output);
}
internal bool ReadOnly { get; set; }
private void CheckReadOnly([CallerMemberName]string? propertyName = null)
{
if (ReadOnly)
{
throw new XmlException(SR.Xml_ReadOnlyProperty, $"{GetType().Name}.{propertyName}");
}
}
[MemberNotNull(nameof(_encoding))]
[MemberNotNull(nameof(_newLineChars))]
[MemberNotNull(nameof(_indentChars))]
private void Initialize()
{
_encoding = Encoding.UTF8;
_omitXmlDecl = false;
_newLineHandling = NewLineHandling.Replace;
_newLineChars = Environment.NewLine; // "\r\n" on Windows, "\n" on Unix
IndentInternal = TriState.Unknown;
_indentChars = " ";
_newLineOnAttributes = false;
_closeOutput = false;
_namespaceHandling = NamespaceHandling.Default;
_conformanceLevel = ConformanceLevel.Document;
_checkCharacters = true;
_writeEndDocumentOnClose = true;
OutputMethod = XmlOutputMethod.Xml;
CDataSectionElements.Clear();
_mergeCDataSections = false;
_mediaType = null;
_docTypeSystem = null;
_docTypePublic = null;
_standalone = XmlStandalone.Omit;
_doNotEscapeUriAttributes = false;
_useAsync = false;
ReadOnly = false;
}
private XmlWriter AddConformanceWrapper(XmlWriter baseWriter)
{
ConformanceLevel confLevel = ConformanceLevel.Auto;
XmlWriterSettings? baseWriterSettings = baseWriter.Settings;
bool checkValues = false;
bool checkNames = false;
bool replaceNewLines = false;
bool needWrap = false;
if (baseWriterSettings == null)
{
// assume the V1 writer already do all conformance checking;
// wrap only if NewLineHandling == Replace or CheckCharacters is true
if (_newLineHandling == NewLineHandling.Replace)
{
replaceNewLines = true;
needWrap = true;
}
if (_checkCharacters)
{
checkValues = true;
needWrap = true;
}
}
else
{
if (_conformanceLevel != baseWriterSettings.ConformanceLevel)
{
confLevel = ConformanceLevel;
needWrap = true;
}
if (_checkCharacters && !baseWriterSettings.CheckCharacters)
{
checkValues = true;
checkNames = confLevel == ConformanceLevel.Auto;
needWrap = true;
}
if (_newLineHandling == NewLineHandling.Replace &&
baseWriterSettings.NewLineHandling == NewLineHandling.None)
{
replaceNewLines = true;
needWrap = true;
}
}
XmlWriter writer = baseWriter;
if (needWrap)
{
if (confLevel != ConformanceLevel.Auto)
{
writer = new XmlWellFormedWriter(writer, this);
}
if (checkValues || replaceNewLines)
{
writer = new XmlCharCheckingWriter(writer, checkValues, checkNames, replaceNewLines, this.NewLineChars);
}
}
if (this.IsQuerySpecific && (baseWriterSettings == null || !baseWriterSettings.IsQuerySpecific))
{
// Create QueryOutputWriterV1 if CData sections or DocType need to be tracked
writer = new QueryOutputWriterV1(writer, this);
}
return writer;
}
/// <summary>
/// Serialize the object to BinaryWriter.
/// </summary>
internal void GetObjectData(XmlQueryDataWriter writer)
{
// Encoding encoding;
// NOTE: For Encoding we serialize only CodePage, and ignore EncoderFallback/DecoderFallback.
// It suffices for XSLT purposes, but not in the general case.
Debug.Assert(Encoding.Equals(Encoding.GetEncoding(Encoding.CodePage)), "Cannot serialize encoding correctly");
writer.Write(Encoding.CodePage);
// bool omitXmlDecl;
writer.Write(OmitXmlDeclaration);
// NewLineHandling newLineHandling;
writer.Write((sbyte)NewLineHandling);
// string newLineChars;
writer.WriteStringQ(NewLineChars);
// TriState indent;
writer.Write((sbyte)IndentInternal);
// string indentChars;
writer.WriteStringQ(IndentChars);
// bool newLineOnAttributes;
writer.Write(NewLineOnAttributes);
// bool closeOutput;
writer.Write(CloseOutput);
// ConformanceLevel conformanceLevel;
writer.Write((sbyte)ConformanceLevel);
// bool checkCharacters;
writer.Write(CheckCharacters);
// XmlOutputMethod outputMethod;
writer.Write((sbyte)OutputMethod);
// List<XmlQualifiedName> cdataSections;
writer.Write(CDataSectionElements.Count);
foreach (XmlQualifiedName qName in CDataSectionElements)
{
writer.Write(qName.Name);
writer.Write(qName.Namespace);
}
// bool mergeCDataSections;
writer.Write(_mergeCDataSections);
// string mediaType;
writer.WriteStringQ(_mediaType);
// string docTypeSystem;
writer.WriteStringQ(_docTypeSystem);
// string docTypePublic;
writer.WriteStringQ(_docTypePublic);
// XmlStandalone standalone;
writer.Write((sbyte)_standalone);
// bool autoXmlDecl;
writer.Write(_autoXmlDecl);
// bool isReadOnly;
writer.Write(ReadOnly);
}
/// <summary>
/// Deserialize the object from BinaryReader.
/// </summary>
internal XmlWriterSettings(XmlQueryDataReader reader)
{
// Encoding encoding;
Encoding = Encoding.GetEncoding(reader.ReadInt32());
// bool omitXmlDecl;
OmitXmlDeclaration = reader.ReadBoolean();
// NewLineHandling newLineHandling;
NewLineHandling = (NewLineHandling)reader.ReadSByte(0, (sbyte)NewLineHandling.None);
// string newLineChars;
NewLineChars = reader.ReadStringQ()!;
// TriState indent;
IndentInternal = (TriState)reader.ReadSByte((sbyte)TriState.Unknown, (sbyte)TriState.True);
// string indentChars;
IndentChars = reader.ReadStringQ()!;
// bool newLineOnAttributes;
NewLineOnAttributes = reader.ReadBoolean();
// bool closeOutput;
CloseOutput = reader.ReadBoolean();
// ConformanceLevel conformanceLevel;
ConformanceLevel = (ConformanceLevel)reader.ReadSByte(0, (sbyte)ConformanceLevel.Document);
// bool checkCharacters;
CheckCharacters = reader.ReadBoolean();
// XmlOutputMethod outputMethod;
OutputMethod = (XmlOutputMethod)reader.ReadSByte(0, (sbyte)XmlOutputMethod.AutoDetect);
// List<XmlQualifiedName> cdataSections;
int length = reader.ReadInt32();
CDataSectionElements = new List<XmlQualifiedName>(length);
for (int idx = 0; idx < length; idx++)
{
CDataSectionElements.Add(new XmlQualifiedName(reader.ReadString(), reader.ReadString()));
}
// bool mergeCDataSections;
_mergeCDataSections = reader.ReadBoolean();
// string mediaType;
_mediaType = reader.ReadStringQ();
// string docTypeSystem;
_docTypeSystem = reader.ReadStringQ();
// string docTypePublic;
_docTypePublic = reader.ReadStringQ();
// XmlStandalone standalone;
Standalone = (XmlStandalone)reader.ReadSByte(0, (sbyte)XmlStandalone.No);
// bool autoXmlDecl;
_autoXmlDecl = reader.ReadBoolean();
// bool isReadOnly;
ReadOnly = reader.ReadBoolean();
}
[DoesNotReturn]
[StackTraceHidden]
private static void ThrowArgumentOutOfRangeException(string paramName)
{
throw new ArgumentOutOfRangeException(paramName);
}
}
}