Add a more functional (i.e. fewer-stubs) implementation of System.Data.Linq.
[mono.git] / mcs / class / System.Xml.Linq / System.Xml.Linq / XElement.cs
1 //
2 // Authors:
3 //   Atsushi Enomoto
4 //
5 // Copyright 2007 Novell (http://www.novell.com)
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining
8 // a copy of this software and associated documentation files (the
9 // "Software"), to deal in the Software without restriction, including
10 // without limitation the rights to use, copy, modify, merge, publish,
11 // distribute, sublicense, and/or sell copies of the Software, and to
12 // permit persons to whom the Software is furnished to do so, subject to
13 // the following conditions:
14 // 
15 // The above copyright notice and this permission notice shall be
16 // included in all copies or substantial portions of the Software.
17 // 
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 //
26
27 using System;
28 using System.Collections;
29 using System.Collections.Generic;
30 using System.IO;
31 using System.Text;
32 using System.Xml;
33 using System.Xml.Schema;
34 using System.Xml.Serialization;
35
36 namespace System.Xml.Linq
37 {
38         [XmlSchemaProvider (null, IsAny = true)]
39         public class XElement : XContainer, IXmlSerializable
40         {
41                 static IEnumerable <XElement> emptySequence =
42                         new List <XElement> ();
43
44                 public static IEnumerable <XElement> EmptySequence {
45                         get { return emptySequence; }
46                 }
47
48                 XName name;
49                 XAttribute attr_first, attr_last;
50                 bool explicit_is_empty = true;
51
52                 public XElement (XName name, object value)
53                 {
54                         this.name = name;
55                         Add (value);
56                 }
57
58                 public XElement (XElement source)
59                 {
60                         name = source.name;
61                         Add (source.Attributes ());
62                         Add (source.Nodes ());
63                 }
64
65                 public XElement (XName name)
66                 {
67                         this.name = name;
68                 }
69
70                 public XElement (XName name, params object [] contents)
71                 {
72                         this.name = name;
73                         Add (contents);
74                 }
75
76                 public XElement (XStreamingElement source)
77                 {
78                         this.name = source.Name;
79                         Add (source.Contents);
80                 }
81
82                 public static explicit operator bool (XElement element)
83                 {
84                         if (element == null)
85                                 throw new ArgumentNullException ("element");
86                         return XmlConvert.ToBoolean (element.Value);
87                 }
88
89                 public static explicit operator bool? (XElement element)
90                 {
91                         if (element == null)
92                                 return null;
93                         
94                         return element.Value == null ? (bool?) null : XmlConvert.ToBoolean (element.Value);
95                 }
96
97                 public static explicit operator DateTime (XElement element)
98                 {
99                         if (element == null)
100                                 throw new ArgumentNullException ("element");
101                         return XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
102                 }
103
104                 public static explicit operator DateTime? (XElement element)
105                 {
106                         if (element == null)
107                                 return null;
108                         
109                         return element.Value == null ? (DateTime?) null : XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
110                 }
111
112                 public static explicit operator decimal (XElement element)
113                 {
114                         if (element == null)
115                                 throw new ArgumentNullException ("element");
116                         return XmlConvert.ToDecimal (element.Value);
117                 }
118
119                 public static explicit operator decimal? (XElement element)
120                 {
121                         if (element == null)
122                                 return null;
123                         
124                         return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
125                 }
126
127                 public static explicit operator double (XElement element)
128                 {
129                         if (element == null)
130                                 throw new ArgumentNullException ("element");
131                         return XmlConvert.ToDouble (element.Value);
132                 }
133
134                 public static explicit operator double? (XElement element)
135                 {
136                         if (element == null)
137                                 return null;
138                         
139                         return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
140                 }
141
142                 public static explicit operator float (XElement element)
143                 {
144                         if (element == null)
145                                 throw new ArgumentNullException ("element");
146                         return XmlConvert.ToSingle (element.Value);
147                 }
148
149                 public static explicit operator float? (XElement element)
150                 {
151                         if (element == null)
152                                 return null;
153                         
154                         return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
155                 }
156
157                 public static explicit operator Guid (XElement element)
158                 {
159                         if (element == null)
160                                 throw new ArgumentNullException ("element");
161                         return XmlConvert.ToGuid (element.Value);
162                 }
163
164                 public static explicit operator Guid? (XElement element)
165                 {
166                         if (element == null)
167                                 return null;
168                         
169                         return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
170                 }
171
172                 public static explicit operator int (XElement element)
173                 {
174                         if (element == null)
175                                 throw new ArgumentNullException ("element");
176                         return XmlConvert.ToInt32 (element.Value);
177                 }
178
179                 public static explicit operator int? (XElement element)
180                 {
181                         if (element == null)
182                                 return null;
183                         
184                         return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
185                 }
186
187                 public static explicit operator long (XElement element)
188                 {
189                         if (element == null)
190                                 throw new ArgumentNullException ("element");
191                         return XmlConvert.ToInt64 (element.Value);
192                 }
193
194                 public static explicit operator long? (XElement element)
195                 {
196                         if (element == null)
197                                 return null;
198                         
199                         return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
200                 }
201
202                 [CLSCompliant (false)]
203                 public static explicit operator uint (XElement element)
204                 {
205                         if (element == null)
206                                 throw new ArgumentNullException ("element");
207                         return XmlConvert.ToUInt32 (element.Value);
208                 }
209
210                 [CLSCompliant (false)]
211                 public static explicit operator uint? (XElement element)
212                 {
213                         if (element == null)
214                                 return null;
215                         
216                         return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
217                 }
218
219                 [CLSCompliant (false)]
220                 public static explicit operator ulong (XElement element)
221                 {
222                         if (element == null)
223                                 throw new ArgumentNullException ("element");
224                         return XmlConvert.ToUInt64 (element.Value);
225                 }
226
227                 [CLSCompliant (false)]
228                 public static explicit operator ulong? (XElement element)
229                 {
230                         if (element == null)
231                                 return null;
232                         
233                         return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
234                 }
235
236                 public static explicit operator TimeSpan (XElement element)
237                 {
238                         if (element == null)
239                                 throw new ArgumentNullException ("element");
240                         return XmlConvert.ToTimeSpan (element.Value);
241                 }
242
243                 public static explicit operator TimeSpan? (XElement element)
244                 {
245                         if (element == null)
246                                 return null;
247                         
248                         return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
249                 }
250
251                 public static explicit operator string (XElement element)
252                 {
253                         if (element == null)
254                                 return null;
255                         
256                         return element.Value;
257                 }
258
259                 public XAttribute FirstAttribute {
260                         get { return attr_first; }
261                         internal set { attr_first = value; }
262                 }
263
264                 public XAttribute LastAttribute {
265                         get { return attr_last; }
266                         internal set { attr_last = value; }
267                 }
268
269                 public bool HasAttributes {
270                         get { return attr_first != null; }
271                 }
272
273                 public bool HasElements {
274                         get {
275                                 foreach (object o in Nodes ())
276                                         if (o is XElement)
277                                                 return true;
278                                 return false;
279                         }
280                 }
281
282                 public bool IsEmpty {
283                         get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
284                         internal set { explicit_is_empty = value; }
285                 }
286
287                 public XName Name {
288                         get { return name; }
289                         set {
290                                 if (name == null)
291                                         throw new ArgumentNullException ("value");
292                                 name = value;
293                         }
294                 }
295
296                 public override XmlNodeType NodeType {
297                         get { return XmlNodeType.Element; }
298                 }
299
300                 public string Value {
301                         get {
302                                 StringBuilder sb = null;
303                                 foreach (XNode n in Nodes ()) {
304                                         if (sb == null)
305                                                 sb = new StringBuilder ();
306                                         if (n is XText)
307                                                 sb.Append (((XText) n).Value);
308                                         else if (n is XElement)
309                                                 sb.Append (((XElement) n).Value);
310                                 }
311                                 return sb == null ? String.Empty : sb.ToString ();
312                         }
313                         set {
314                                 RemoveNodes ();
315                                 Add (value);
316                         }
317                 }
318
319                 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
320                 {
321                         List <XElement> list = new List <XElement> ();
322                         if (getMeIn)
323                                 list.Add (this);
324                         for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
325                                 if (name == null || el.Name == name)
326                                         list.Add (el);
327                         return list;
328                 }
329
330                 public XAttribute Attribute (XName name)
331                 {
332                         foreach (XAttribute a in Attributes ())
333                                 if (a.Name == name)
334                                         return a;
335                         return null;
336                 }
337
338                 public IEnumerable <XAttribute> Attributes ()
339                 {
340                         XAttribute next;
341                         for (XAttribute a = attr_first; a != null; a = next) {
342                                 next = a.NextAttribute;
343                                 yield return a;
344                         }
345                 }
346
347                 // huh?
348                 public IEnumerable <XAttribute> Attributes (XName name)
349                 {
350                         foreach (XAttribute a in Attributes ())
351                                 if (a.Name == name)
352                                         yield return a;
353                 }
354
355                 public static XElement Load (string uri)
356                 {
357                         return Load (uri, LoadOptions.None);
358                 }
359
360                 public static XElement Load (string uri, LoadOptions options)
361                 {
362                         XmlReaderSettings s = new XmlReaderSettings ();
363                         s.ProhibitDtd = false;
364                         s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
365                         using (XmlReader r = XmlReader.Create (uri, s)) {
366                                 return LoadCore (r, options);
367                         }
368                 }
369
370                 public static XElement Load (TextReader tr)
371                 {
372                         return Load (tr, LoadOptions.None);
373                 }
374
375                 public static XElement Load (TextReader tr, LoadOptions options)
376                 {
377                         XmlReaderSettings s = new XmlReaderSettings ();
378                         s.ProhibitDtd = false;
379                         s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
380                         using (XmlReader r = XmlReader.Create (tr, s)) {
381                                 return LoadCore (r, options);
382                         }
383                 }
384
385                 public static XElement Load (XmlReader reader)
386                 {
387                         return Load (reader, LoadOptions.None);
388                 }
389
390                 public static XElement Load (XmlReader reader, LoadOptions options)
391                 {
392                         XmlReaderSettings s = reader.Settings.Clone ();
393                         s.ProhibitDtd = false;
394                         s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
395                         using (XmlReader r = XmlReader.Create (reader, s)) {
396                                 return LoadCore (r, options);
397                         }
398                 }
399
400                 internal static XElement LoadCore (XmlReader r, LoadOptions options)
401                 {
402                         r.MoveToContent ();
403                         if (r.NodeType != XmlNodeType.Element)
404                                 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
405                         XName name = XName.Get (r.LocalName, r.NamespaceURI);
406                         XElement e = new XElement (name);
407                         e.FillLineInfoAndBaseUri (r, options);
408
409                         if (r.MoveToFirstAttribute ()) {
410                                 do {
411                                         // not sure how current Orcas behavior makes sense here though ...
412                                         if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
413                                                 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
414                                         else
415                                                 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
416                                         e.LastAttribute.FillLineInfoAndBaseUri (r, options);
417                                 } while (r.MoveToNextAttribute ());
418                                 r.MoveToElement ();
419                         }
420                         if (!r.IsEmptyElement) {
421                                 r.Read ();
422                                 e.ReadContentFrom (r, options);
423                                 r.ReadEndElement ();
424                                 e.explicit_is_empty = false;
425                         } else {
426                                 e.explicit_is_empty = true;
427                                 r.Read ();
428                         }
429                         return e;
430                 }
431
432                 public static XElement Parse (string s)
433                 {
434                         return Parse (s, LoadOptions.None);
435                 }
436
437                 public static XElement Parse (string s, LoadOptions options)
438                 {
439                         return Load (new StringReader (s), options);
440                 }
441
442                 public void RemoveAll ()
443                 {
444                         RemoveAttributes ();
445                         RemoveNodes ();
446                 }
447
448                 public void RemoveAttributes ()
449                 {
450                         while (attr_first != null)
451                                 attr_last.Remove ();
452                 }
453
454                 public void Save (string filename)
455                 {
456                         Save (filename, SaveOptions.None);
457                 }
458
459                 public void Save (string filename, SaveOptions options)
460                 {
461                         XmlWriterSettings s = new XmlWriterSettings ();
462                         s.Indent = options != SaveOptions.DisableFormatting;
463                         using (XmlWriter w = XmlWriter.Create (filename, s)) {
464                                 Save (w);
465                         }
466                 }
467
468                 public void Save (TextWriter tw)
469                 {
470                         Save (tw, SaveOptions.None);
471                 }
472
473                 public void Save (TextWriter tw, SaveOptions options)
474                 {
475                         XmlWriterSettings s = new XmlWriterSettings ();
476                         s.Indent = options != SaveOptions.DisableFormatting;
477                         using (XmlWriter w = XmlWriter.Create (tw, s)) {
478                                 Save (w);
479                         }
480                 }
481
482                 public void Save (XmlWriter w)
483                 {
484                         WriteTo (w);
485                 }
486
487                 public IEnumerable <XElement> AncestorsAndSelf ()
488                 {
489                         return GetAncestorList (null, true);
490                 }
491
492                 public IEnumerable <XElement> AncestorsAndSelf (XName name)
493                 {
494                         return GetAncestorList (name, true);
495                 }
496
497                 public IEnumerable <XElement> DescendantsAndSelf ()
498                 {
499                         List <XElement> list = new List <XElement> ();
500                         list.Add (this);
501                         list.AddRange (Descendants ());
502                         return list;
503                 }
504
505                 public IEnumerable <XElement> DescendantsAndSelf (XName name)
506                 {
507                         List <XElement> list = new List <XElement> ();
508                         if (name == this.name)
509                                 list.Add (this);
510                         list.AddRange (Descendants (name));
511                         return list;
512                 }
513
514                 public IEnumerable <XNode> DescendantNodesAndSelf ()
515                 {
516                         yield return this;
517                         foreach (XNode node in DescendantNodes ())
518                                 yield return node;
519                 }
520
521                 public void SetAttributeValue (XName name, object value)
522                 {
523                         XAttribute a = Attribute (name);
524                         if (value == null) {
525                                 if (a != null)
526                                         a.Remove ();
527                         } else {
528                                 if (a == null) {
529                                         SetAttributeObject (new XAttribute (name, value));
530                                 }
531                                 else
532                                         a.Value = XUtil.ToString (value);
533                         }
534                 }
535
536                 void SetAttributeObject (XAttribute a)
537                 {
538                         a = (XAttribute) XUtil.GetDetachedObject (a);
539                         a.SetOwner (this);
540                         if (attr_first == null) {
541                                 attr_first = a;
542                                 attr_last = a;
543                         } else {
544                                 attr_last.NextAttribute = a;
545                                 a.PreviousAttribute = attr_last;
546                                 attr_last = a;
547                         }
548                 }
549
550                 public override void WriteTo (XmlWriter w)
551                 {
552                         // some people expect the same prefix output as in input,
553                         // in the loss of performance... see bug #466423.
554                         string prefix = name.NamespaceName.Length > 0 ? w.LookupPrefix (name.Namespace.NamespaceName) : String.Empty;
555                         foreach (XAttribute a in Attributes ()) {
556                                 if (a.IsNamespaceDeclaration && a.Value == name.Namespace.NamespaceName) {
557                                         if (a.Name.Namespace == XNamespace.Xmlns)
558                                                 prefix = a.Name.LocalName;
559                                         // otherwise xmlns="..."
560                                         break;
561                                 }
562                         }
563
564                         w.WriteStartElement (prefix, name.LocalName, name.Namespace.NamespaceName);
565
566                         foreach (XAttribute a in Attributes ()) {
567                                 if (a.IsNamespaceDeclaration) {
568                                         if (a.Name.Namespace == XNamespace.Xmlns)
569                                                 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
570                                         else
571                                                 w.WriteAttributeString ("xmlns", a.Value);
572                                 }
573                                 else
574                                         w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
575                         }
576
577                         foreach (XNode node in Nodes ())
578                                 node.WriteTo (w);
579
580                         if (explicit_is_empty)
581                                 w.WriteEndElement ();
582                         else
583                                 w.WriteFullEndElement ();
584                 }
585
586                 public XNamespace GetDefaultNamespace ()
587                 {
588                         for (XElement el = this; el != null; el = el.Parent)
589                                 foreach (XAttribute a in el.Attributes ())
590                                         if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
591                                                 return XNamespace.Get (a.Value);
592                         return XNamespace.None; // nothing is declared.
593                 }
594
595                 public XNamespace GetNamespaceOfPrefix (string prefix)
596                 {
597                         for (XElement el = this; el != null; el = el.Parent)
598                                 foreach (XAttribute a in el.Attributes ())
599                                         if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix)
600                                                 return XNamespace.Get (a.Value);
601                         return XNamespace.None; // nothing is declared.
602                 }
603
604                 public string GetPrefixOfNamespace (XNamespace ns)
605                 {
606                         foreach (string prefix in GetPrefixOfNamespaceCore (ns))
607                                 if (GetNamespaceOfPrefix (prefix) == ns)
608                                         return prefix;
609                         return null; // nothing is declared
610                 }
611                 
612                 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
613                 {
614                         for (XElement el = this; el != null; el = el.Parent)
615                                 foreach (XAttribute a in el.Attributes ())
616                                         if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
617                                                 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
618                 }
619
620                 public void ReplaceAll (object item)
621                 {
622                         RemoveNodes ();
623                         Add (item);
624                 }
625
626                 public void ReplaceAll (params object [] items)
627                 {
628                         RemoveNodes ();
629                         Add (items);
630                 }
631
632                 public void ReplaceAttributes (object item)
633                 {
634                         RemoveAttributes ();
635                         Add (item);
636                 }
637
638                 public void ReplaceAttributes (params object [] items)
639                 {
640                         RemoveAttributes ();
641                         Add (items);
642                 }
643
644                 public void SetElementValue (XName name, object value)
645                 {
646                         XElement el = new XElement (name, value);
647                         RemoveNodes ();
648                         Add (el);
649                 }
650
651                 public void SetValue (object value)
652                 {
653                         if (value == null)
654                                 throw new ArgumentNullException ("value");
655                         if (value is XAttribute || value is XDocument || value is XDeclaration || value is XDocumentType)
656                                 throw new ArgumentException (String.Format ("Node type {0} is not allowed as element value", value.GetType ()));
657                         RemoveNodes ();
658                         foreach (object o in XUtil.ExpandArray (value))
659                                 Add (o);
660                 }
661
662                 internal override bool OnAddingObject (object o, bool rejectAttribute, XNode refNode, bool addFirst)
663                 {
664                         if (o is XDocument || o is XDocumentType || o is XDeclaration || (rejectAttribute && o is XAttribute))
665                                 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", o.GetType ()));
666
667                         XAttribute a = o as XAttribute;
668                         if (a != null) {
669                                 foreach (XAttribute ia in Attributes ())
670                                         if (a.Name == ia.Name)
671                                                 throw new InvalidOperationException (String.Format ("Duplicate attribute: {0}", a.Name));
672                                 SetAttributeObject (a);
673                                 return true;
674                         }
675                         else if (o is string && refNode is XText) {
676                                 ((XText) refNode).Value += o as string;
677                                 return true;
678                         }
679                         else
680                                 return false;
681                 }
682
683                 void IXmlSerializable.WriteXml (XmlWriter writer)
684                 {
685                         Save (writer);
686                 }
687
688                 void IXmlSerializable.ReadXml (XmlReader reader)
689                 {
690                         ReadContentFrom (reader, LoadOptions.None);
691                 }
692
693                 XmlSchema IXmlSerializable.GetSchema ()
694                 {
695                         return null;
696                 }
697         }
698 }