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;
34 using System.Xml.Schema;
35 using System.Xml.Serialization;
37 namespace System.Xml.Linq
39 [XmlSchemaProvider (null, IsAny = true)]
40 public class XElement : XContainer, IXmlSerializable
42 static IEnumerable <XElement> emptySequence =
43 new List <XElement> ();
45 public static IEnumerable <XElement> EmptySequence {
46 get { return emptySequence; }
50 XAttribute attr_first, attr_last;
51 bool explicit_is_empty = true;
53 public XElement (XName name, object content)
59 public XElement (XElement other)
62 Add (other.Attributes ());
66 public XElement (XName name)
71 public XElement (XName name, params object [] content)
77 public XElement (XStreamingElement other)
79 this.name = other.Name;
83 [CLSCompliant (false)]
84 public static explicit operator bool (XElement element)
87 throw new ArgumentNullException ("element");
88 return XUtil.ConvertToBoolean (element.Value);
91 [CLSCompliant (false)]
92 public static explicit operator bool? (XElement element)
97 return element.Value == null ? (bool?) null : XUtil.ConvertToBoolean (element.Value);
100 [CLSCompliant (false)]
101 public static explicit operator DateTime (XElement element)
104 throw new ArgumentNullException ("element");
105 return XUtil.ToDateTime (element.Value);
108 [CLSCompliant (false)]
109 public static explicit operator DateTime? (XElement element)
114 return element.Value == null ? (DateTime?) null : XUtil.ToDateTime (element.Value);
117 #if !TARGET_JVM // Same as for System.Xml.XmlConvert.ToDateTimeOffset
119 [CLSCompliant (false)]
120 public static explicit operator DateTimeOffset (XElement element)
123 throw new ArgumentNullException ("element");
124 return XmlConvert.ToDateTimeOffset (element.Value);
127 [CLSCompliant (false)]
128 public static explicit operator DateTimeOffset? (XElement element)
133 return element.Value == null ? (DateTimeOffset?) null : XmlConvert.ToDateTimeOffset (element.Value);
138 [CLSCompliant (false)]
139 public static explicit operator decimal (XElement element)
142 throw new ArgumentNullException ("element");
143 return XmlConvert.ToDecimal (element.Value);
146 [CLSCompliant (false)]
147 public static explicit operator decimal? (XElement element)
152 return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
155 [CLSCompliant (false)]
156 public static explicit operator double (XElement element)
159 throw new ArgumentNullException ("element");
160 return XmlConvert.ToDouble (element.Value);
163 [CLSCompliant (false)]
164 public static explicit operator double? (XElement element)
169 return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
172 [CLSCompliant (false)]
173 public static explicit operator float (XElement element)
176 throw new ArgumentNullException ("element");
177 return XmlConvert.ToSingle (element.Value);
180 [CLSCompliant (false)]
181 public static explicit operator float? (XElement element)
186 return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
189 [CLSCompliant (false)]
190 public static explicit operator Guid (XElement element)
193 throw new ArgumentNullException ("element");
194 return XmlConvert.ToGuid (element.Value);
197 [CLSCompliant (false)]
198 public static explicit operator Guid? (XElement element)
203 return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
206 [CLSCompliant (false)]
207 public static explicit operator int (XElement element)
210 throw new ArgumentNullException ("element");
211 return XmlConvert.ToInt32 (element.Value);
214 [CLSCompliant (false)]
215 public static explicit operator int? (XElement element)
220 return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
223 [CLSCompliant (false)]
224 public static explicit operator long (XElement element)
227 throw new ArgumentNullException ("element");
228 return XmlConvert.ToInt64 (element.Value);
231 [CLSCompliant (false)]
232 public static explicit operator long? (XElement element)
237 return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
240 [CLSCompliant (false)]
241 public static explicit operator uint (XElement element)
244 throw new ArgumentNullException ("element");
245 return XmlConvert.ToUInt32 (element.Value);
248 [CLSCompliant (false)]
249 public static explicit operator uint? (XElement element)
254 return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
257 [CLSCompliant (false)]
258 public static explicit operator ulong (XElement element)
261 throw new ArgumentNullException ("element");
262 return XmlConvert.ToUInt64 (element.Value);
265 [CLSCompliant (false)]
266 public static explicit operator ulong? (XElement element)
271 return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
274 [CLSCompliant (false)]
275 public static explicit operator TimeSpan (XElement element)
278 throw new ArgumentNullException ("element");
279 return XmlConvert.ToTimeSpan (element.Value);
282 [CLSCompliant (false)]
283 public static explicit operator TimeSpan? (XElement element)
288 return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
291 [CLSCompliant (false)]
292 public static explicit operator string (XElement element)
297 return element.Value;
300 public XAttribute FirstAttribute {
301 get { return attr_first; }
302 internal set { attr_first = value; }
305 public XAttribute LastAttribute {
306 get { return attr_last; }
307 internal set { attr_last = value; }
310 public bool HasAttributes {
311 get { return attr_first != null; }
314 public bool HasElements {
316 foreach (object o in Nodes ())
323 public bool IsEmpty {
324 get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
325 internal set { explicit_is_empty = value; }
332 throw new ArgumentNullException ("Name");
333 OnNameChanging (this);
335 OnNameChanged (this);
339 public override XmlNodeType NodeType {
340 get { return XmlNodeType.Element; }
343 public string Value {
345 StringBuilder sb = null;
346 foreach (XNode n in Nodes ()) {
348 sb = new StringBuilder ();
350 sb.Append (((XText) n).Value);
351 else if (n is XElement)
352 sb.Append (((XElement) n).Value);
354 return sb == null ? String.Empty : sb.ToString ();
362 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
364 List <XElement> list = new List <XElement> ();
367 for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
368 if (name == null || el.Name == name)
373 public XAttribute Attribute (XName name)
375 foreach (XAttribute a in Attributes ())
381 public IEnumerable <XAttribute> Attributes ()
384 for (XAttribute a = attr_first; a != null; a = next) {
385 next = a.NextAttribute;
391 public IEnumerable <XAttribute> Attributes (XName name)
393 foreach (XAttribute a in Attributes ())
398 static void DefineDefaultSettings (XmlReaderSettings settings, LoadOptions options)
401 // 2.1 has a DtdProcessing property which defaults to DtdProcessing.Prohibit
402 settings.DtdProcessing = DtdProcessing.Parse;
404 settings.ProhibitDtd = false;
407 settings.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
410 static XmlReaderSettings CreateDefaultSettings (LoadOptions options)
412 var settings = new XmlReaderSettings ();
413 DefineDefaultSettings (settings, options);
417 public static XElement Load (string uri)
419 return Load (uri, LoadOptions.None);
422 public static XElement Load (string uri, LoadOptions options)
424 XmlReaderSettings s = CreateDefaultSettings (options);
426 using (XmlReader r = XmlReader.Create (uri, s)) {
427 return LoadCore (r, options);
431 public static XElement Load (TextReader textReader)
433 return Load (textReader, LoadOptions.None);
436 public static XElement Load (TextReader textReader, LoadOptions options)
438 XmlReaderSettings s = CreateDefaultSettings (options);
440 using (XmlReader r = XmlReader.Create (textReader, s)) {
441 return LoadCore (r, options);
445 public static XElement Load (XmlReader reader)
447 return Load (reader, LoadOptions.None);
450 public static XElement Load (XmlReader reader, LoadOptions options)
452 XmlReaderSettings s = reader.Settings != null ? reader.Settings.Clone () : new XmlReaderSettings ();
453 DefineDefaultSettings (s, options);
455 using (XmlReader r = XmlReader.Create (reader, s)) {
456 return LoadCore (r, options);
460 #if MOONLIGHT || MOBILE || NET_4_0
461 public static XElement Load (Stream stream)
463 return Load (stream, LoadOptions.None);
466 public static XElement Load (Stream stream, LoadOptions options)
468 XmlReaderSettings s = new XmlReaderSettings ();
469 DefineDefaultSettings (s, options);
471 using (XmlReader r = XmlReader.Create (stream, s)) {
472 return LoadCore (r, options);
477 internal static XElement LoadCore (XmlReader r, LoadOptions options)
480 if (r.NodeType != XmlNodeType.Element)
481 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
482 XName name = XName.Get (r.LocalName, r.NamespaceURI);
483 XElement e = new XElement (name);
484 e.FillLineInfoAndBaseUri (r, options);
486 if (r.MoveToFirstAttribute ()) {
488 // not sure how current Orcas behavior makes sense here though ...
489 if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
490 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
492 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
493 e.LastAttribute.FillLineInfoAndBaseUri (r, options);
494 } while (r.MoveToNextAttribute ());
497 if (!r.IsEmptyElement) {
499 e.ReadContentFrom (r, options);
501 e.explicit_is_empty = false;
503 e.explicit_is_empty = true;
509 public static XElement Parse (string text)
511 return Parse (text, LoadOptions.None);
514 public static XElement Parse (string text, LoadOptions options)
516 return Load (new StringReader (text), options);
519 public void RemoveAll ()
525 public void RemoveAttributes ()
527 while (attr_first != null)
531 public void Save (string fileName)
533 Save (fileName, SaveOptions.None);
536 public void Save (string fileName, SaveOptions options)
538 XmlWriterSettings s = new XmlWriterSettings ();
540 if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
542 #if NET_4_0 || MOONLIGHT || MOBILE
543 if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
544 s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
546 using (XmlWriter w = XmlWriter.Create (fileName, s)) {
551 public void Save (TextWriter textWriter)
553 Save (textWriter, SaveOptions.None);
556 public void Save (TextWriter textWriter, SaveOptions options)
558 XmlWriterSettings s = new XmlWriterSettings ();
560 if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
562 #if NET_4_0 || MOONLIGHT || MOBILE
563 if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
564 s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
566 using (XmlWriter w = XmlWriter.Create (textWriter, s)) {
571 public void Save (XmlWriter writer)
576 #if NET_4_0 || MOONLIGHT || MOBILE
577 public void Save (Stream stream)
579 Save (stream, SaveOptions.None);
582 public void Save (Stream stream, SaveOptions options)
584 XmlWriterSettings s = new XmlWriterSettings ();
585 if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
587 if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
588 s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
590 using (var writer = XmlWriter.Create (stream, s)){
595 public IEnumerable <XElement> AncestorsAndSelf ()
597 return GetAncestorList (null, true);
600 public IEnumerable <XElement> AncestorsAndSelf (XName name)
602 return GetAncestorList (name, true);
605 public IEnumerable <XElement> DescendantsAndSelf ()
607 List <XElement> list = new List <XElement> ();
609 list.AddRange (Descendants ());
613 public IEnumerable <XElement> DescendantsAndSelf (XName name)
615 List <XElement> list = new List <XElement> ();
616 if (name == this.name)
618 list.AddRange (Descendants (name));
622 public IEnumerable <XNode> DescendantNodesAndSelf ()
625 foreach (XNode node in DescendantNodes ())
629 public void SetAttributeValue (XName name, object value)
631 XAttribute a = Attribute (name);
637 SetAttributeObject (new XAttribute (name, value));
640 a.Value = XUtil.ToString (value);
644 void SetAttributeObject (XAttribute a)
647 a = (XAttribute) XUtil.GetDetachedObject (a);
649 if (attr_first == null) {
653 attr_last.NextAttribute = a;
654 a.PreviousAttribute = attr_last;
660 string LookupPrefix (string ns, XmlWriter w)
662 string prefix = ns.Length > 0 ? GetPrefixOfNamespace (ns) ?? w.LookupPrefix (ns) : String.Empty;
663 foreach (XAttribute a in Attributes ()) {
664 if (a.IsNamespaceDeclaration && a.Value == ns) {
665 if (a.Name.Namespace == XNamespace.Xmlns)
666 prefix = a.Name.LocalName;
667 // otherwise xmlns="..."
674 static string CreateDummyNamespace (ref int createdNS, IEnumerable<XAttribute> atts, bool isAttr)
676 if (!isAttr && atts.All (a => a.Name.LocalName != "xmlns" || a.Name.NamespaceName == XNamespace.Xmlns.NamespaceName))
680 p = "p" + (++createdNS);
682 if (atts.All (a => a.Name.LocalName != p || a.Name.NamespaceName == XNamespace.Xmlns.NamespaceName))
688 public override void WriteTo (XmlWriter writer)
690 // some people expect the same prefix output as in input,
691 // in the loss of performance... see bug #466423.
692 string prefix = LookupPrefix (name.NamespaceName, writer);
695 prefix = CreateDummyNamespace (ref createdNS, Attributes (), false);
697 writer.WriteStartElement (prefix, name.LocalName, name.Namespace.NamespaceName);
699 foreach (XAttribute a in Attributes ()) {
700 if (a.IsNamespaceDeclaration) {
701 if (a.Name.Namespace == XNamespace.Xmlns)
702 writer.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
704 writer.WriteAttributeString ("xmlns", a.Value);
706 string apfix = LookupPrefix (a.Name.NamespaceName, writer);
708 apfix = CreateDummyNamespace (ref createdNS, Attributes (), true);
709 writer.WriteAttributeString (apfix, a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
713 foreach (XNode node in Nodes ())
714 node.WriteTo (writer);
716 if (explicit_is_empty)
717 writer.WriteEndElement ();
719 writer.WriteFullEndElement ();
722 public XNamespace GetDefaultNamespace ()
724 for (XElement el = this; el != null; el = el.Parent)
725 foreach (XAttribute a in el.Attributes ())
726 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
727 return XNamespace.Get (a.Value);
728 return XNamespace.None; // nothing is declared.
731 public XNamespace GetNamespaceOfPrefix (string prefix)
733 for (XElement el = this; el != null; el = el.Parent)
734 foreach (XAttribute a in el.Attributes ())
735 if (a.IsNamespaceDeclaration && (prefix.Length == 0 && a.Name.LocalName == "xmlns" || a.Name.LocalName == prefix))
736 return XNamespace.Get (a.Value);
737 return XNamespace.None; // nothing is declared.
740 public string GetPrefixOfNamespace (XNamespace ns)
742 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
743 if (GetNamespaceOfPrefix (prefix) == ns)
745 return null; // nothing is declared
748 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
750 for (XElement el = this; el != null; el = el.Parent)
751 foreach (XAttribute a in el.Attributes ())
752 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
753 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
756 public void ReplaceAll (object content)
762 public void ReplaceAll (params object [] content)
768 public void ReplaceAttributes (object content)
774 public void ReplaceAttributes (params object [] content)
780 public void SetElementValue (XName name, object value)
782 var element = Element (name);
783 if (element == null && value != null) {
784 Add (new XElement (name, value));
785 } else if (element != null && value == null) {
788 element.SetValue (value);
791 public void SetValue (object value)
794 throw new ArgumentNullException ("value");
795 if (value is XAttribute || value is XDocument || value is XDeclaration || value is XDocumentType)
796 throw new ArgumentException (String.Format ("Node type {0} is not allowed as element value", value.GetType ()));
798 foreach (object o in XUtil.ExpandArray (value))
802 internal override bool OnAddingObject (object o, bool rejectAttribute, XNode refNode, bool addFirst)
804 if (o is XDocument || o is XDocumentType || o is XDeclaration || (rejectAttribute && o is XAttribute))
805 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", o.GetType ()));
807 XAttribute a = o as XAttribute;
809 foreach (XAttribute ia in Attributes ())
810 if (a.Name == ia.Name)
811 throw new InvalidOperationException (String.Format ("Duplicate attribute: {0}", a.Name));
812 SetAttributeObject (a);
815 else if (o is string && refNode is XText) {
816 ((XText) refNode).Value += o as string;
823 void IXmlSerializable.WriteXml (XmlWriter writer)
828 void IXmlSerializable.ReadXml (XmlReader reader)
830 ReadContentFrom (reader, LoadOptions.None);
833 XmlSchema IXmlSerializable.GetSchema ()