-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathXElement.cs
More file actions
2130 lines (1974 loc) · 82.1 KB
/
XElement.cs
File metadata and controls
2130 lines (1974 loc) · 82.1 KB
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
// 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.CodeAnalysis;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Xml.Schema;
using CultureInfo = System.Globalization.CultureInfo;
using IEnumerable = System.Collections.IEnumerable;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
using StringBuilder = System.Text.StringBuilder;
using System.Diagnostics;
namespace System.Xml.Linq
{
/// <summary>
/// Represents an XML element.
/// </summary>
/// <remarks>
/// An element has an <see cref="XName"/>, optionally one or more attributes,
/// and can optionally contain content (see <see cref="XContainer.Nodes"/>.
/// An <see cref="XElement"/> can contain the following types of content:
/// <list>
/// <item>string (Text content)</item>
/// <item><see cref="XElement"/></item>
/// <item><see cref="XComment"/></item>
/// <item><see cref="XProcessingInstruction"/></item>
/// </list>
/// </remarks>
[XmlSchemaProvider(null, IsAny = true)]
[System.ComponentModel.TypeDescriptionProvider("MS.Internal.Xml.Linq.ComponentModel.XTypeDescriptionProvider`1[[System.Xml.Linq.XElement, System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],System.ComponentModel.TypeConverter")]
public class XElement : XContainer, IXmlSerializable
{
/// <summary>
/// Gets an empty collection of elements.
/// </summary>
public static IEnumerable<XElement> EmptySequence
{
get
{
return Array.Empty<XElement>();
}
}
internal XName name = null!;
internal XAttribute? lastAttr;
/// <summary>
/// Initializes a new instance of the XElement class with the specified name.
/// </summary>
/// <param name="name">
/// The name of the element.
/// </param>
public XElement(XName name)
{
ArgumentNullException.ThrowIfNull(name);
this.name = name;
}
/// <summary>
/// Initializes a new instance of the XElement class with the specified name and content.
/// </summary>
/// <param name="name">
/// The element name.
/// </param>
/// <param name="content">The initial contents of the element.</param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public XElement(XName name, object? content)
: this(name)
{
AddContentSkipNotify(content);
}
/// <summary>
/// Initializes a new instance of the XElement class with the specified name and content.
/// </summary>
/// <param name="name">
/// The element name.
/// </param>
/// <param name="content">
/// The initial content of the element.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public XElement(XName name, params object?[] content) : this(name, (object)content) { }
/// <summary>
/// Initializes a new instance of the XElement class from another XElement object.
/// </summary>
/// <param name="other">
/// Another element that will be copied to this element.
/// </param>
/// <remarks>
/// This constructor makes a deep copy from one element to another.
/// </remarks>
public XElement(XElement other)
: base(other)
{
this.name = other.name;
XAttribute? a = other.lastAttr;
if (a != null)
{
do
{
a = a.next!;
AppendAttributeSkipNotify(new XAttribute(a));
} while (a != other.lastAttr);
}
}
/// <summary>
/// Initializes an XElement object from an <see cref="XStreamingElement"/> object.
/// </summary>
/// <param name="other">
/// The <see cref="XStreamingElement"/> object whose value will be used
/// to initialize the new element.
/// </param>
public XElement(XStreamingElement other)
{
ArgumentNullException.ThrowIfNull(other);
name = other.name;
AddContentSkipNotify(other.content);
}
internal XElement()
: this("default"!)
{
}
internal XElement(XmlReader r)
: this(r, LoadOptions.None)
{
}
private XElement(AsyncConstructionSentry s)
{
// Dummy ctor used to avoid public default ctor. This is used
// by async methods meant to perform the same operations as
// the XElement constructors that do synchronous processing;
// the async methods instead construct an XElement using this
// constructor (which doesn't do any processing) and then themselves
// do the async processing. This is because ctors can't be 'async'.
}
private struct AsyncConstructionSentry { }
internal XElement(XmlReader r, LoadOptions o)
{
ReadElementFrom(r, o);
}
internal static async Task<XElement> CreateAsync(XmlReader r, CancellationToken cancellationToken)
{
XElement xe = new XElement(default(AsyncConstructionSentry));
await xe.ReadElementFromAsync(r, LoadOptions.None, cancellationToken).ConfigureAwait(false);
return xe;
}
///<overloads>
/// Outputs this <see cref="XElement"/>'s underlying XML tree. The output can
/// be saved to a file, a <see cref="Stream"/>, a <see cref="TextWriter"/>,
/// or an <see cref="XmlWriter"/>. Optionally whitespace can be preserved.
/// </overloads>
/// <summary>
/// Output this <see cref="XElement"/> to a file.
/// </summary>
/// <remarks>
/// The format will be indented by default. If you want
/// no indenting then use the SaveOptions version of Save (see
/// <see cref="XElement.Save(string, SaveOptions)"/>) enabling
/// SaveOptions.DisableFormatting.
/// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations.
/// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </remarks>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
public void Save(string fileName)
{
Save(fileName, GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Output this <see cref="XElement"/> to a file.
/// </summary>
/// <param name="fileName">
/// The name of the file to output the XML to.
/// </param>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
public void Save(string fileName, SaveOptions options)
{
XmlWriterSettings ws = GetXmlWriterSettings(options);
using (XmlWriter w = XmlWriter.Create(fileName, ws))
{
Save(w);
}
}
/// <summary>
/// Gets the first attribute of an element.
/// </summary>
public XAttribute? FirstAttribute
{
get { return lastAttr?.next; }
}
/// <summary>
/// Gets a value indicating whether the element has at least one attribute.
/// </summary>
public bool HasAttributes
{
get { return lastAttr != null; }
}
/// <summary>
/// Gets a value indicating whether the element has at least one child element.
/// </summary>
public bool HasElements
{
get
{
XNode? n = content as XNode;
if (n != null)
{
do
{
if (n is XElement) return true;
n = n.next!;
} while (n != content);
}
return false;
}
}
/// <summary>
/// Gets a value indicating whether the element contains no content.
/// </summary>
public bool IsEmpty
{
get { return content == null; }
}
/// <summary>
/// Gets the last attribute of an element.
/// </summary>
public XAttribute? LastAttribute
{
get { return lastAttr; }
}
/// <summary>
/// Gets the name of this element.
/// </summary>
public XName Name
{
get
{
return name;
}
set
{
ArgumentNullException.ThrowIfNull(value);
bool notify = NotifyChanging(this, XObjectChangeEventArgs.Name);
name = value;
if (notify) NotifyChanged(this, XObjectChangeEventArgs.Name);
}
}
/// <summary>
/// Gets the node type for this node.
/// </summary>
/// <remarks>
/// This property will always return XmlNodeType.Text.
/// </remarks>
public override XmlNodeType NodeType
{
get
{
return XmlNodeType.Element;
}
}
/// <summary>
/// Gets the text contents of this element.
/// </summary>
/// <remarks>
/// If there is text content interspersed with nodes (mixed content) then the text content
/// will be concatenated and returned.
/// </remarks>
public string Value
{
get
{
if (content == null) return string.Empty;
string? s = content as string;
if (s != null) return s;
StringBuilder sb = StringBuilderCache.Acquire();
AppendText(sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
set
{
ArgumentNullException.ThrowIfNull(value);
RemoveNodes();
Add(value);
}
}
/// <overloads>
/// Returns this <see cref="XElement"/> and all of it's ancestors up
/// to the root node. Optionally an <see cref="XName"/> can be passed
/// in to target a specific ancestor(s).
/// <seealso cref="XNode.Ancestors()"/>
/// </overloads>
/// <summary>
/// Returns this <see cref="XElement"/> and all of it's ancestors up to
/// the root node.
/// <seealso cref="XNode.Ancestors()"/>
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing all of
/// this <see cref="XElement"/>'s ancestors up to the root node (including
/// this <see cref="XElement"/>.
/// </returns>
public IEnumerable<XElement> AncestorsAndSelf()
{
return GetAncestors(null, true);
}
/// <summary>
/// Returns the ancestor(s) of this <see cref="XElement"/> with the matching
/// <see cref="XName"/>. If this <see cref="XElement"/>'s <see cref="XName"/>
/// matches the <see cref="XName"/> passed in then it will be included in the
/// resulting <see cref="IEnumerable"/> or <see cref="XElement"/>.
/// <seealso cref="XNode.Ancestors()"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> of the target ancestor.
/// </param>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing the
/// ancestors of this <see cref="XElement"/> with a matching <see cref="XName"/>.
/// </returns>
public IEnumerable<XElement> AncestorsAndSelf(XName? name)
{
return name != null ? GetAncestors(name, true) : XElement.EmptySequence;
}
/// <summary>
/// Returns the <see cref="XAttribute"/> associated with this <see cref="XElement"/> that has this
/// <see cref="XName"/>.
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> of the <see cref="XAttribute"/> to get.
/// </param>
/// <returns>
/// The <see cref="XAttribute"/> with the <see cref="XName"/> passed in. If there is no <see cref="XAttribute"/>
/// with this <see cref="XName"/> then null is returned.
/// </returns>
public XAttribute? Attribute(XName name)
{
XAttribute? a = lastAttr;
if (a != null)
{
do
{
a = a.next!;
if (a.name == name) return a;
} while (a != lastAttr);
}
return null;
}
/// <overloads>
/// Returns the <see cref="XAttribute"/> associated with this <see cref="XElement"/>. Optionally
/// an <see cref="XName"/> can be given to target a specific <see cref="XAttribute"/>(s).
/// </overloads>
/// <summary>
/// Returns all of the <see cref="XAttribute"/>s associated with this <see cref="XElement"/>.
/// <seealso cref="XContainer.Elements()"/>
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XAttribute"/> containing all of the <see cref="XAttribute"/>s
/// associated with this <see cref="XElement"/>.
/// </returns>
public IEnumerable<XAttribute> Attributes()
{
return GetAttributes(null);
}
/// <summary>
/// Returns the <see cref="XAttribute"/>(s) associated with this <see cref="XElement"/> that has the passed
/// in <see cref="XName"/>.
/// <seealso cref="XElement.Attributes()"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> of the targeted <see cref="XAttribute"/>.
/// </param>
/// <returns>
/// The <see cref="XAttribute"/>(s) with the matching
/// </returns>
public IEnumerable<XAttribute> Attributes(XName? name)
{
return name != null ? GetAttributes(name) : XAttribute.EmptySequence;
}
/// <summary>
/// Get the self and descendant nodes for an <see cref="XElement"/>
/// </summary>
/// <returns></returns>
public IEnumerable<XNode> DescendantNodesAndSelf()
{
return GetDescendantNodes(true);
}
/// <overloads>
/// Returns this <see cref="XElement"/> and all of it's descendants. Overloads allow
/// specification of a type of descendant to return, or a specific <see cref="XName"/>
/// of a descendant <see cref="XElement"/> to match.
/// </overloads>
/// <summary>
/// Returns this <see cref="XElement"/> and all of it's descendant <see cref="XElement"/>s
/// as an <see cref="IEnumerable"/> of <see cref="XElement"/>.
/// <seealso cref="XElement.DescendantsAndSelf()"/>
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing this <see cref="XElement"/>
/// and all of it's descendants.
/// </returns>
public IEnumerable<XElement> DescendantsAndSelf()
{
return GetDescendants(null, true);
}
/// <summary>
/// Returns the descendants of this <see cref="XElement"/> that have a matching <see cref="XName"/>
/// to the one passed in, including, potentially, this <see cref="XElement"/>.
/// <seealso cref="XElement.DescendantsAndSelf(XName)"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> of the descendant <see cref="XElement"/> that is being targeted.
/// </param>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> containing all of the descendant
/// <see cref="XElement"/>s that have this <see cref="XName"/>.
/// </returns>
public IEnumerable<XElement> DescendantsAndSelf(XName? name)
{
return name != null ? GetDescendants(name, true) : XElement.EmptySequence;
}
/// <summary>
/// Returns the default <see cref="XNamespace"/> of an <see cref="XElement"/>
/// </summary>
public XNamespace GetDefaultNamespace()
{
string? namespaceName = GetNamespaceOfPrefixInScope("xmlns", null);
return namespaceName != null ? XNamespace.Get(namespaceName) : XNamespace.None;
}
/// <summary>
/// Get the namespace associated with a particular prefix for this <see cref="XElement"/>
/// in its document context.
/// </summary>
/// <param name="prefix">The namespace prefix to look up</param>
/// <returns>An <see cref="XNamespace"/> for the namespace bound to the prefix</returns>
public XNamespace? GetNamespaceOfPrefix(string prefix)
{
ArgumentException.ThrowIfNullOrEmpty(prefix);
if (prefix == "xmlns") return XNamespace.Xmlns;
string? namespaceName = GetNamespaceOfPrefixInScope(prefix, null);
if (namespaceName != null) return XNamespace.Get(namespaceName);
if (prefix == "xml") return XNamespace.Xml;
return null;
}
/// <summary>
/// Get the prefix associated with a namespace for an element in its context.
/// </summary>
/// <param name="ns">The <see cref="XNamespace"/> for which to get a prefix</param>
/// <returns>The namespace prefix string</returns>
public string? GetPrefixOfNamespace(XNamespace ns)
{
ArgumentNullException.ThrowIfNull(ns);
string namespaceName = ns.NamespaceName;
bool hasInScopeNamespace = false;
XElement? e = this;
do
{
XAttribute? a = e.lastAttr;
if (a != null)
{
bool hasLocalNamespace = false;
do
{
a = a.next!;
if (a.IsNamespaceDeclaration)
{
if (a.Value == namespaceName)
{
if (a.Name.NamespaceName.Length != 0 &&
(!hasInScopeNamespace ||
GetNamespaceOfPrefixInScope(a.Name.LocalName, e) == null))
{
return a.Name.LocalName;
}
}
hasLocalNamespace = true;
}
}
while (a != e.lastAttr);
hasInScopeNamespace |= hasLocalNamespace;
}
e = e.parent as XElement;
}
while (e != null);
if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace)
{
if (!hasInScopeNamespace || GetNamespaceOfPrefixInScope("xml", null) == null) return "xml";
}
else if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace)
{
return "xmlns";
}
return null;
}
/// <overloads>
/// The Load method provides multiple strategies for creating a new
/// <see cref="XElement"/> and initializing it from a data source containing
/// raw XML. Load from a file (passing in a URI to the file), an
/// <see cref="Stream"/>, a <see cref="TextReader"/>, or an
/// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/>
/// to create an <see cref="XDocument"/> from a string containing XML.
/// <seealso cref="XDocument.Load(string)" />
/// <seealso cref="XElement.Parse(string)"/>
/// </overloads>
/// <summary>
/// Create a new <see cref="XElement"/> based on the contents of the file
/// referenced by the URI parameter passed in. Note: Use
/// <see cref="XElement.Parse(string)"/> to create an <see cref="XElement"/> from
/// a string containing XML.
/// <seealso cref="XmlReader.Create(string)"/>
/// <seealso cref="XElement.Parse(string)"/>
/// <seealso cref="XDocument.Parse(string)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into the underlying
/// XML tree.
/// </remarks>
/// <param name="uri">
/// A URI string referencing the file to load into a new <see cref="XElement"/>.
/// </param>
/// <returns>
/// An <see cref="XElement"/> initialized with the contents of the file referenced
/// in the passed in uri parameter.
/// </returns>
public static XElement Load([StringSyntax(StringSyntaxAttribute.Uri)] string uri)
{
return Load(uri, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XElement"/> based on the contents of the file
/// referenced by the URI parameter passed in. Optionally, whitespace can be preserved.
/// <see cref="XmlReader.Create(string)"/>
/// <seealso cref="XDocument.Load(string, LoadOptions)"/>
/// </summary>
/// <remarks>
/// This method uses the <see cref="XmlReader.Create(string)"/> method to create
/// an <see cref="XmlReader"/> to read the raw XML into an underlying
/// XML tree. If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="uri">
/// A string representing the URI of the file to be loaded into a new <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XElement"/> initialized with the contents of the file referenced
/// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then
/// significant whitespace will be preserved.
/// </returns>
public static XElement Load([StringSyntax(StringSyntaxAttribute.Uri)] string uri, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(uri, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter.
/// </summary>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XElement Load(Stream stream)
{
return Load(stream, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static XElement Load(Stream stream, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(stream, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="Stream"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.</param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="Stream"/>.
/// </returns>
public static async Task<XElement> LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
rs.Async = true;
using (XmlReader r = XmlReader.Create(stream, rs))
{
return await LoadAsync(r, options, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter.
/// </summary>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XElement Load(TextReader textReader)
{
return Load(textReader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static XElement Load(TextReader textReader, LoadOptions options)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(textReader, rs))
{
return Load(r, options);
}
}
/// <summary>
/// Create a new <see cref="XElement"/> and initialize its underlying XML tree using
/// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling
/// can be preserved.
/// </summary>
/// <remarks>
/// If LoadOptions.PreserveWhitespace is enabled then
/// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/>
/// is set to false.
/// </remarks>
/// <param name="textReader">
/// A <see cref="TextReader"/> containing the raw XML to read into the newly
/// created <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.</param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed in
/// <see cref="TextReader"/>.
/// </returns>
public static async Task<XElement> LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken)
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
rs.Async = true;
using (XmlReader r = XmlReader.Create(textReader, rs))
{
return await LoadAsync(r, options, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Create a new <see cref="XElement"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XElement"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XElement Load(XmlReader reader)
{
return Load(reader, LoadOptions.None);
}
/// <summary>
/// Create a new <see cref="XElement"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static XElement Load(XmlReader reader, LoadOptions options)
{
ArgumentNullException.ThrowIfNull(reader);
if (reader.MoveToContent() != XmlNodeType.Element) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ExpectedNodeType, XmlNodeType.Element, reader.NodeType));
XElement e = new XElement(reader, options);
reader.MoveToContent();
if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
return e;
}
/// <summary>
/// Create a new <see cref="XElement"/> containing the contents of the
/// passed in <see cref="XmlReader"/>.
/// </summary>
/// <param name="reader">
/// An <see cref="XmlReader"/> containing the XML to be read into the new
/// <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <param name="cancellationToken">
/// A cancellation token.</param>
/// <returns>
/// A new <see cref="XElement"/> containing the contents of the passed
/// in <see cref="XmlReader"/>.
/// </returns>
public static Task<XElement> LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(reader);
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<XElement>(cancellationToken);
return LoadAsyncInternal(reader, options, cancellationToken);
}
private static async Task<XElement> LoadAsyncInternal(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
{
if (await reader.MoveToContentAsync().ConfigureAwait(false) != XmlNodeType.Element) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ExpectedNodeType, XmlNodeType.Element, reader.NodeType));
XElement e = new XElement(default(AsyncConstructionSentry));
await e.ReadElementFromAsync(reader, options, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
await reader.MoveToContentAsync().ConfigureAwait(false);
if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile);
return e;
}
/// <overloads>
/// Parses a string containing XML into an <see cref="XElement"/>. Optionally
/// whitespace can be preserved.
/// </overloads>
/// <summary>
/// Parses a string containing XML into an <see cref="XElement"/>.
/// </summary>
/// <remarks>
/// The XML must contain only one root node.
/// </remarks>
/// <param name="text">
/// A string containing the XML to parse into an <see cref="XElement"/>.
/// </param>
/// <returns>
/// An <see cref="XElement"/> created from the XML string passed in.
/// </returns>
public static XElement Parse(string text)
{
return Parse(text, LoadOptions.None);
}
/// <summary>
/// Parses a string containing XML into an <see cref="XElement"/> and optionally
/// preserves the Whitespace. See <see cref="XmlReaderSettings.IgnoreWhitespace"/>.
/// </summary>
/// <remarks>
/// <list>
/// <item>The XML must contain only one root node.</item>
/// <item>
/// If LoadOptions.PreserveWhitespace is enabled the underlying
/// <see cref="XmlReaderSettings"/>'
/// property <see cref="XmlReaderSettings.IgnoreWhitespace"/> will be set to false.
/// </item>
/// </list>
/// </remarks>
/// <param name="text">
/// A string containing the XML to parse into an <see cref="XElement"/>.
/// </param>
/// <param name="options">
/// A set of <see cref="LoadOptions"/>.
/// </param>
/// <returns>
/// An <see cref="XElement"/> created from the XML string passed in.
/// </returns>
public static XElement Parse(string text, LoadOptions options)
{
using (StringReader sr = new StringReader(text))
{
XmlReaderSettings rs = GetXmlReaderSettings(options);
using (XmlReader r = XmlReader.Create(sr, rs))
{
return Load(r, options);
}
}
}
/// <summary>
/// Removes content and attributes from this <see cref="XElement"/>.
/// <seealso cref="XElement.RemoveAttributes"/>
/// <seealso cref="XContainer.RemoveNodes"/>
/// </summary>
public void RemoveAll()
{
RemoveAttributes();
RemoveNodes();
}
/// <summary>
/// Removes that attributes of this <see cref="XElement"/>.
/// <seealso cref="XElement.RemoveAll"/>
/// <seealso cref="XElement.RemoveAttributes"/>
/// </summary>
public void RemoveAttributes()
{
if (SkipNotify())
{
RemoveAttributesSkipNotify();
return;
}
while (lastAttr != null)
{
XAttribute a = lastAttr.next!;
NotifyChanging(a, XObjectChangeEventArgs.Remove);
if (lastAttr == null || a != lastAttr.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
if (a != lastAttr)
{
lastAttr.next = a.next;
}
else
{
lastAttr = null;
}
a.parent = null;
a.next = null;
NotifyChanged(a, XObjectChangeEventArgs.Remove);
}
}
/// <overloads>
/// Replaces the child nodes and the attributes of this element with the
/// specified content. The content can be simple content, a collection of
/// content objects, a parameter list of content objects, or null.
/// </overloads>
/// <summary>
/// Replaces the children nodes and the attributes of this element with the specified content.
/// </summary>
/// <param name="content">
/// The content that will replace the child nodes and attributes of this element.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceAll(object? content)
{
content = GetContentSnapshot(content);
RemoveAll();
Add(content);
}
/// <summary>
/// Replaces the children nodes and the attributes of this element with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceAll(params object?[] content)
{
ReplaceAll((object)content);
}
/// <overloads>
/// Replaces the attributes of this element with the specified content.
/// The content can be simple content, a collection of
/// content objects, a parameter list of content objects, or null.
/// </overloads>
/// <summary>
/// Replaces the attributes of this element with the specified content.