5 // Copyright 2007 Novell (http://www.novell.com)
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:
15 // The above copyright notice and this permission notice shall be
16 // included in all copies or substantial portions of the Software.
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.
28 using System.Collections;
29 using System.Collections.Generic;
33 using System.Xml.Schema;
34 using System.Xml.Serialization;
36 namespace System.Xml.Linq
38 [XmlSchemaProvider (null, IsAny = true)]
39 public class XElement : XContainer, IXmlSerializable
41 static IEnumerable <XElement> emptySequence =
42 new List <XElement> ();
44 public static IEnumerable <XElement> EmptySequence {
45 get { return emptySequence; }
49 XAttribute attr_first, attr_last;
50 bool explicit_is_empty = true;
52 public XElement (XName name, object value)
58 public XElement (XElement source)
61 Add (source.Attributes ());
62 Add (source.Nodes ());
65 public XElement (XName name)
70 public XElement (XName name, params object [] contents)
76 public XElement (XStreamingElement source)
78 this.name = source.Name;
79 Add (source.Contents);
82 public static explicit operator bool (XElement element)
85 throw new ArgumentNullException ("element");
86 return XUtil.ConvertToBoolean (element.Value);
89 public static explicit operator bool? (XElement element)
94 return element.Value == null ? (bool?) null : XUtil.ConvertToBoolean (element.Value);
97 public static explicit operator DateTime (XElement element)
100 throw new ArgumentNullException ("element");
101 return XUtil.ToDateTime (element.Value);
104 public static explicit operator DateTime? (XElement element)
109 return element.Value == null ? (DateTime?) null : XUtil.ToDateTime (element.Value);
112 #if !TARGET_JVM // Same as for System.Xml.XmlConvert.ToDateTimeOffset
114 public static explicit operator DateTimeOffset (XElement element)
117 throw new ArgumentNullException ("element");
118 return XmlConvert.ToDateTimeOffset (element.Value);
121 public static explicit operator DateTimeOffset? (XElement element)
126 return element.Value == null ? (DateTimeOffset?) null : XmlConvert.ToDateTimeOffset (element.Value);
131 public static explicit operator decimal (XElement element)
134 throw new ArgumentNullException ("element");
135 return XmlConvert.ToDecimal (element.Value);
138 public static explicit operator decimal? (XElement element)
143 return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
146 public static explicit operator double (XElement element)
149 throw new ArgumentNullException ("element");
150 return XmlConvert.ToDouble (element.Value);
153 public static explicit operator double? (XElement element)
158 return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
161 public static explicit operator float (XElement element)
164 throw new ArgumentNullException ("element");
165 return XmlConvert.ToSingle (element.Value);
168 public static explicit operator float? (XElement element)
173 return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
176 public static explicit operator Guid (XElement element)
179 throw new ArgumentNullException ("element");
180 return XmlConvert.ToGuid (element.Value);
183 public static explicit operator Guid? (XElement element)
188 return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
191 public static explicit operator int (XElement element)
194 throw new ArgumentNullException ("element");
195 return XmlConvert.ToInt32 (element.Value);
198 public static explicit operator int? (XElement element)
203 return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
206 public static explicit operator long (XElement element)
209 throw new ArgumentNullException ("element");
210 return XmlConvert.ToInt64 (element.Value);
213 public static explicit operator long? (XElement element)
218 return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
221 [CLSCompliant (false)]
222 public static explicit operator uint (XElement element)
225 throw new ArgumentNullException ("element");
226 return XmlConvert.ToUInt32 (element.Value);
229 [CLSCompliant (false)]
230 public static explicit operator uint? (XElement element)
235 return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
238 [CLSCompliant (false)]
239 public static explicit operator ulong (XElement element)
242 throw new ArgumentNullException ("element");
243 return XmlConvert.ToUInt64 (element.Value);
246 [CLSCompliant (false)]
247 public static explicit operator ulong? (XElement element)
252 return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
255 public static explicit operator TimeSpan (XElement element)
258 throw new ArgumentNullException ("element");
259 return XmlConvert.ToTimeSpan (element.Value);
262 public static explicit operator TimeSpan? (XElement element)
267 return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
270 public static explicit operator string (XElement element)
275 return element.Value;
278 public XAttribute FirstAttribute {
279 get { return attr_first; }
280 internal set { attr_first = value; }
283 public XAttribute LastAttribute {
284 get { return attr_last; }
285 internal set { attr_last = value; }
288 public bool HasAttributes {
289 get { return attr_first != null; }
292 public bool HasElements {
294 foreach (object o in Nodes ())
301 public bool IsEmpty {
302 get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
303 internal set { explicit_is_empty = value; }
310 throw new ArgumentNullException ("value");
315 public override XmlNodeType NodeType {
316 get { return XmlNodeType.Element; }
319 public string Value {
321 StringBuilder sb = null;
322 foreach (XNode n in Nodes ()) {
324 sb = new StringBuilder ();
326 sb.Append (((XText) n).Value);
327 else if (n is XElement)
328 sb.Append (((XElement) n).Value);
330 return sb == null ? String.Empty : sb.ToString ();
338 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
340 List <XElement> list = new List <XElement> ();
343 for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
344 if (name == null || el.Name == name)
349 public XAttribute Attribute (XName name)
351 foreach (XAttribute a in Attributes ())
357 public IEnumerable <XAttribute> Attributes ()
360 for (XAttribute a = attr_first; a != null; a = next) {
361 next = a.NextAttribute;
367 public IEnumerable <XAttribute> Attributes (XName name)
369 foreach (XAttribute a in Attributes ())
374 static void DefineDefaultSettings (XmlReaderSettings settings, LoadOptions options)
376 #if NET_2_1 && !MONOTOUCH
377 // 2.1 has a DtdProcessing property which defaults to DtdProcessing.Prohibit
378 settings.DtdProcessing = DtdProcessing.Parse;
380 settings.ProhibitDtd = false;
383 settings.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
386 static XmlReaderSettings CreateDefaultSettings (LoadOptions options)
388 var settings = new XmlReaderSettings ();
389 DefineDefaultSettings (settings, options);
393 public static XElement Load (string uri)
395 return Load (uri, LoadOptions.None);
398 public static XElement Load (string uri, LoadOptions options)
400 XmlReaderSettings s = CreateDefaultSettings (options);
402 using (XmlReader r = XmlReader.Create (uri, s)) {
403 return LoadCore (r, options);
407 public static XElement Load (TextReader tr)
409 return Load (tr, LoadOptions.None);
412 public static XElement Load (TextReader tr, LoadOptions options)
414 XmlReaderSettings s = CreateDefaultSettings (options);
416 using (XmlReader r = XmlReader.Create (tr, s)) {
417 return LoadCore (r, options);
421 public static XElement Load (XmlReader reader)
423 return Load (reader, LoadOptions.None);
426 public static XElement Load (XmlReader reader, LoadOptions options)
428 XmlReaderSettings s = reader.Settings != null ? reader.Settings.Clone () : new XmlReaderSettings ();
429 DefineDefaultSettings (s, options);
431 using (XmlReader r = XmlReader.Create (reader, s)) {
432 return LoadCore (r, options);
436 internal static XElement LoadCore (XmlReader r, LoadOptions options)
439 if (r.NodeType != XmlNodeType.Element)
440 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
441 XName name = XName.Get (r.LocalName, r.NamespaceURI);
442 XElement e = new XElement (name);
443 e.FillLineInfoAndBaseUri (r, options);
445 if (r.MoveToFirstAttribute ()) {
447 // not sure how current Orcas behavior makes sense here though ...
448 if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
449 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
451 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
452 e.LastAttribute.FillLineInfoAndBaseUri (r, options);
453 } while (r.MoveToNextAttribute ());
456 if (!r.IsEmptyElement) {
458 e.ReadContentFrom (r, options);
460 e.explicit_is_empty = false;
462 e.explicit_is_empty = true;
468 public static XElement Parse (string s)
470 return Parse (s, LoadOptions.None);
473 public static XElement Parse (string s, LoadOptions options)
475 return Load (new StringReader (s), options);
478 public void RemoveAll ()
484 public void RemoveAttributes ()
486 while (attr_first != null)
490 public void Save (string filename)
492 Save (filename, SaveOptions.None);
495 public void Save (string filename, SaveOptions options)
497 XmlWriterSettings s = new XmlWriterSettings ();
498 s.Indent = options != SaveOptions.DisableFormatting;
499 using (XmlWriter w = XmlWriter.Create (filename, s)) {
504 public void Save (TextWriter tw)
506 Save (tw, SaveOptions.None);
509 public void Save (TextWriter tw, SaveOptions options)
511 XmlWriterSettings s = new XmlWriterSettings ();
512 s.Indent = options != SaveOptions.DisableFormatting;
513 using (XmlWriter w = XmlWriter.Create (tw, s)) {
518 public void Save (XmlWriter w)
523 public IEnumerable <XElement> AncestorsAndSelf ()
525 return GetAncestorList (null, true);
528 public IEnumerable <XElement> AncestorsAndSelf (XName name)
530 return GetAncestorList (name, true);
533 public IEnumerable <XElement> DescendantsAndSelf ()
535 List <XElement> list = new List <XElement> ();
537 list.AddRange (Descendants ());
541 public IEnumerable <XElement> DescendantsAndSelf (XName name)
543 List <XElement> list = new List <XElement> ();
544 if (name == this.name)
546 list.AddRange (Descendants (name));
550 public IEnumerable <XNode> DescendantNodesAndSelf ()
553 foreach (XNode node in DescendantNodes ())
557 public void SetAttributeValue (XName name, object value)
559 XAttribute a = Attribute (name);
565 SetAttributeObject (new XAttribute (name, value));
568 a.Value = XUtil.ToString (value);
572 void SetAttributeObject (XAttribute a)
574 a = (XAttribute) XUtil.GetDetachedObject (a);
576 if (attr_first == null) {
580 attr_last.NextAttribute = a;
581 a.PreviousAttribute = attr_last;
586 public override void WriteTo (XmlWriter w)
588 // some people expect the same prefix output as in input,
589 // in the loss of performance... see bug #466423.
590 string prefix = name.NamespaceName.Length > 0 ? w.LookupPrefix (name.Namespace.NamespaceName) : String.Empty;
591 foreach (XAttribute a in Attributes ()) {
592 if (a.IsNamespaceDeclaration && a.Value == name.Namespace.NamespaceName) {
593 if (a.Name.Namespace == XNamespace.Xmlns)
594 prefix = a.Name.LocalName;
595 // otherwise xmlns="..."
600 w.WriteStartElement (prefix, name.LocalName, name.Namespace.NamespaceName);
602 foreach (XAttribute a in Attributes ()) {
603 if (a.IsNamespaceDeclaration) {
604 if (a.Name.Namespace == XNamespace.Xmlns)
605 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
607 w.WriteAttributeString ("xmlns", a.Value);
610 w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
613 foreach (XNode node in Nodes ())
616 if (explicit_is_empty)
617 w.WriteEndElement ();
619 w.WriteFullEndElement ();
622 public XNamespace GetDefaultNamespace ()
624 for (XElement el = this; el != null; el = el.Parent)
625 foreach (XAttribute a in el.Attributes ())
626 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
627 return XNamespace.Get (a.Value);
628 return XNamespace.None; // nothing is declared.
631 public XNamespace GetNamespaceOfPrefix (string prefix)
633 for (XElement el = this; el != null; el = el.Parent)
634 foreach (XAttribute a in el.Attributes ())
635 if (a.IsNamespaceDeclaration && (prefix.Length == 0 && a.Name.LocalName == "xmlns" || a.Name.LocalName == prefix))
636 return XNamespace.Get (a.Value);
637 return XNamespace.None; // nothing is declared.
640 public string GetPrefixOfNamespace (XNamespace ns)
642 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
643 if (GetNamespaceOfPrefix (prefix) == ns)
645 return null; // nothing is declared
648 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
650 for (XElement el = this; el != null; el = el.Parent)
651 foreach (XAttribute a in el.Attributes ())
652 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
653 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
656 public void ReplaceAll (object item)
662 public void ReplaceAll (params object [] items)
668 public void ReplaceAttributes (object item)
674 public void ReplaceAttributes (params object [] items)
680 public void SetElementValue (XName name, object value)
682 XElement el = new XElement (name, value);
687 public void SetValue (object value)
690 throw new ArgumentNullException ("value");
691 if (value is XAttribute || value is XDocument || value is XDeclaration || value is XDocumentType)
692 throw new ArgumentException (String.Format ("Node type {0} is not allowed as element value", value.GetType ()));
694 foreach (object o in XUtil.ExpandArray (value))
698 internal override bool OnAddingObject (object o, bool rejectAttribute, XNode refNode, bool addFirst)
700 if (o is XDocument || o is XDocumentType || o is XDeclaration || (rejectAttribute && o is XAttribute))
701 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", o.GetType ()));
703 XAttribute a = o as XAttribute;
705 foreach (XAttribute ia in Attributes ())
706 if (a.Name == ia.Name)
707 throw new InvalidOperationException (String.Format ("Duplicate attribute: {0}", a.Name));
708 SetAttributeObject (a);
711 else if (o is string && refNode is XText) {
712 ((XText) refNode).Value += o as string;
719 void IXmlSerializable.WriteXml (XmlWriter writer)
724 void IXmlSerializable.ReadXml (XmlReader reader)
726 ReadContentFrom (reader, LoadOptions.None);
729 XmlSchema IXmlSerializable.GetSchema ()