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.Nodes ());
64 public XElement (XName name)
69 public XElement (XName name, params object [] contents)
75 public XElement (XStreamingElement source)
77 this.name = source.Name;
78 Add (source.Contents);
81 public static explicit operator bool (XElement element)
84 throw new ArgumentNullException ("element");
85 return XmlConvert.ToBoolean (element.Value);
88 public static explicit operator bool? (XElement element)
93 return element.Value == null ? (bool?) null : XmlConvert.ToBoolean (element.Value);
96 public static explicit operator DateTime (XElement element)
99 throw new ArgumentNullException ("element");
100 return XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
103 public static explicit operator DateTime? (XElement element)
108 return element.Value == null ? (DateTime?) null : XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
111 public static explicit operator decimal (XElement element)
114 throw new ArgumentNullException ("element");
115 return XmlConvert.ToDecimal (element.Value);
118 public static explicit operator decimal? (XElement element)
123 return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
126 public static explicit operator double (XElement element)
129 throw new ArgumentNullException ("element");
130 return XmlConvert.ToDouble (element.Value);
133 public static explicit operator double? (XElement element)
138 return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
141 public static explicit operator float (XElement element)
144 throw new ArgumentNullException ("element");
145 return XmlConvert.ToSingle (element.Value);
148 public static explicit operator float? (XElement element)
153 return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
156 public static explicit operator Guid (XElement element)
159 throw new ArgumentNullException ("element");
160 return XmlConvert.ToGuid (element.Value);
163 public static explicit operator Guid? (XElement element)
168 return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
171 public static explicit operator int (XElement element)
174 throw new ArgumentNullException ("element");
175 return XmlConvert.ToInt32 (element.Value);
178 public static explicit operator int? (XElement element)
183 return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
186 public static explicit operator long (XElement element)
189 throw new ArgumentNullException ("element");
190 return XmlConvert.ToInt64 (element.Value);
193 public static explicit operator long? (XElement element)
198 return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
201 [CLSCompliant (false)]
202 public static explicit operator uint (XElement element)
205 throw new ArgumentNullException ("element");
206 return XmlConvert.ToUInt32 (element.Value);
209 [CLSCompliant (false)]
210 public static explicit operator uint? (XElement element)
215 return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
218 [CLSCompliant (false)]
219 public static explicit operator ulong (XElement element)
222 throw new ArgumentNullException ("element");
223 return XmlConvert.ToUInt64 (element.Value);
226 [CLSCompliant (false)]
227 public static explicit operator ulong? (XElement element)
232 return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
235 public static explicit operator TimeSpan (XElement element)
238 throw new ArgumentNullException ("element");
239 return XmlConvert.ToTimeSpan (element.Value);
242 public static explicit operator TimeSpan? (XElement element)
247 return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
250 public static explicit operator string (XElement element)
255 return element.Value;
258 public XAttribute FirstAttribute {
259 get { return attr_first; }
260 internal set { attr_first = value; }
263 public XAttribute LastAttribute {
264 get { return attr_last; }
265 internal set { attr_last = value; }
268 public bool HasAttributes {
269 get { return attr_first != null; }
272 public bool HasElements {
274 foreach (object o in Nodes ())
281 public bool IsEmpty {
282 get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
283 internal set { explicit_is_empty = value; }
290 throw new ArgumentNullException ("value");
295 public override XmlNodeType NodeType {
296 get { return XmlNodeType.Element; }
299 public string Value {
301 StringBuilder sb = null;
302 foreach (object s in Nodes ()) {
304 sb = new StringBuilder ();
307 return sb == null ? String.Empty : sb.ToString ();
315 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
317 List <XElement> list = new List <XElement> ();
320 for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
321 if (name == null || el.Name == name)
326 public XAttribute Attribute (XName name)
328 foreach (XAttribute a in Attributes ())
334 public IEnumerable <XAttribute> Attributes ()
337 for (XAttribute a = attr_first; a != null; a = next) {
338 next = a.NextAttribute;
344 public IEnumerable <XAttribute> Attributes (XName name)
346 foreach (XAttribute a in Attributes ())
351 public static XElement Load (string uri)
353 return Load (uri, LoadOptions.None);
356 public static XElement Load (string uri, LoadOptions options)
358 XmlReaderSettings s = new XmlReaderSettings ();
359 s.ProhibitDtd = false;
360 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
361 using (XmlReader r = XmlReader.Create (uri, s)) {
362 return LoadCore (r, options);
366 public static XElement Load (TextReader tr)
368 return Load (tr, LoadOptions.None);
371 public static XElement Load (TextReader tr, LoadOptions options)
373 XmlReaderSettings s = new XmlReaderSettings ();
374 s.ProhibitDtd = false;
375 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
376 using (XmlReader r = XmlReader.Create (tr, s)) {
377 return LoadCore (r, options);
381 public static XElement Load (XmlReader reader)
383 return Load (reader, LoadOptions.None);
386 public static XElement Load (XmlReader reader, LoadOptions options)
388 XmlReaderSettings s = reader.Settings.Clone ();
389 s.ProhibitDtd = false;
390 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
391 using (XmlReader r = XmlReader.Create (reader, s)) {
392 return LoadCore (r, options);
396 static XElement LoadCore (XmlReader r, LoadOptions options)
399 if (r.NodeType != XmlNodeType.Element)
400 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
401 XName name = XName.Get (r.LocalName, r.NamespaceURI);
402 XElement e = new XElement (name);
403 e.FillLineInfoAndBaseUri (r, options);
405 if (r.MoveToFirstAttribute ()) {
407 // not sure how current Orcas behavior makes sense here though ...
408 if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
409 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
411 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
412 e.LastAttribute.FillLineInfoAndBaseUri (r, options);
413 } while (r.MoveToNextAttribute ());
416 if (!r.IsEmptyElement) {
418 e.ReadContentFrom (r, options);
420 e.explicit_is_empty = false;
422 e.explicit_is_empty = true;
428 public static XElement Parse (string s)
430 return Parse (s, LoadOptions.None);
433 public static XElement Parse (string s, LoadOptions options)
435 return Load (new StringReader (s), options);
438 public void RemoveAll ()
444 public void RemoveAttributes ()
446 while (attr_first != null)
450 public void Save (string filename)
452 Save (filename, SaveOptions.None);
455 public void Save (string filename, SaveOptions options)
457 XmlWriterSettings s = new XmlWriterSettings ();
458 s.Indent = options != SaveOptions.DisableFormatting;
459 using (XmlWriter w = XmlWriter.Create (filename, s)) {
464 public void Save (TextWriter tw)
466 Save (tw, SaveOptions.None);
469 public void Save (TextWriter tw, SaveOptions options)
471 XmlWriterSettings s = new XmlWriterSettings ();
472 s.Indent = options != SaveOptions.DisableFormatting;
473 using (XmlWriter w = XmlWriter.Create (tw, s)) {
478 public void Save (XmlWriter w)
483 public IEnumerable <XElement> AncestorsAndSelf ()
485 return GetAncestorList (null, true);
488 public IEnumerable <XElement> AncestorsAndSelf (XName name)
490 return GetAncestorList (name, true);
493 public IEnumerable <XElement> DescendantsAndSelf ()
495 List <XElement> list = new List <XElement> ();
497 list.AddRange (Descendants ());
501 public IEnumerable <XElement> DescendantsAndSelf (XName name)
503 List <XElement> list = new List <XElement> ();
504 if (name == this.name)
506 list.AddRange (Descendants (name));
510 public IEnumerable <XNode> DescendantNodesAndSelf ()
513 foreach (XNode node in DescendantNodes ())
517 public void SetAttributeValue (XName name, object value)
519 XAttribute a = Attribute (name);
525 a = new XAttribute (name, value);
527 if (attr_first == null) {
531 attr_last.NextAttribute = a;
532 a.PreviousAttribute = attr_last;
537 a.Value = XUtil.ToString (value);
541 public override void WriteTo (XmlWriter w)
543 w.WriteStartElement (name.LocalName, name.Namespace.NamespaceName);
545 foreach (XAttribute a in Attributes ()) {
546 if (a.IsNamespaceDeclaration) {
547 if (a.Name.Namespace == XNamespace.Xmlns)
548 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
550 w.WriteAttributeString ("xmlns", a.Value);
553 w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
556 foreach (XNode node in Nodes ())
559 if (explicit_is_empty)
560 w.WriteEndElement ();
562 w.WriteFullEndElement ();
565 public XNamespace GetDefaultNamespace ()
567 for (XElement el = this; el != null; el = el.Parent)
568 foreach (XAttribute a in el.Attributes ())
569 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
570 return XNamespace.Get (a.Value);
571 return XNamespace.None; // nothing is declared.
574 public XNamespace GetNamespaceOfPrefix (string prefix)
576 for (XElement el = this; el != null; el = el.Parent)
577 foreach (XAttribute a in el.Attributes ())
578 if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix)
579 return XNamespace.Get (a.Value);
580 return XNamespace.None; // nothing is declared.
583 public string GetPrefixOfNamespace (XNamespace ns)
585 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
586 if (GetNamespaceOfPrefix (prefix) == ns)
588 return null; // nothing is declared
591 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
593 for (XElement el = this; el != null; el = el.Parent)
594 foreach (XAttribute a in el.Attributes ())
595 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
596 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
599 public void ReplaceAll (object item)
605 public void ReplaceAll (params object [] items)
611 public void ReplaceAttributes (object item)
617 public void ReplaceAttributes (params object [] items)
623 public void SetElementValue (XName name, object value)
625 XElement el = new XElement (name, value);
630 public void SetValue (object value)
633 foreach (XNode n in XUtil.ToNodes (value))
637 internal override void OnAdded (XNode node, bool addFirst)
639 if (node is XDocument || node is XDocumentType)
640 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", node.GetType ()));
643 void IXmlSerializable.WriteXml (XmlWriter writer)
648 void IXmlSerializable.ReadXml (XmlReader reader)
650 ReadContentFrom (reader, LoadOptions.None);
653 XmlSchema IXmlSerializable.GetSchema ()