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)
76 public XElement (XStreamingElement source)
78 this.name = source.Name;
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 if ((options & SaveOptions.DisableFormatting) != 0) {
461 s.IndentChars = String.Empty;
462 s.NewLineChars = String.Empty;
464 using (XmlWriter w = XmlWriter.Create (filename)) {
469 public void Save (TextWriter tw)
471 Save (tw, SaveOptions.None);
474 public void Save (TextWriter tw, SaveOptions options)
476 XmlWriterSettings s = new XmlWriterSettings ();
477 if ((options & SaveOptions.DisableFormatting) != 0) {
480 s.IndentChars = String.Empty;
481 s.NewLineChars = String.Empty;
483 using (XmlWriter w = XmlWriter.Create (tw)) {
488 public void Save (XmlWriter w)
493 public IEnumerable <XElement> AncestorsAndSelf ()
495 return GetAncestorList (null, true);
498 public IEnumerable <XElement> AncestorsAndSelf (XName name)
500 return GetAncestorList (name, true);
503 public IEnumerable <XElement> DescendantsAndSelf ()
505 List <XElement> list = new List <XElement> ();
507 list.AddRange (Descendants ());
511 public IEnumerable <XElement> DescendantsAndSelf (XName name)
513 List <XElement> list = new List <XElement> ();
514 if (name == this.name)
516 list.AddRange (Descendants (name));
520 public IEnumerable <XNode> DescendantNodesAndSelf ()
523 foreach (XNode node in DescendantNodes ())
527 public void SetAttributeValue (XName name, object value)
529 XAttribute a = Attribute (name);
535 a = new XAttribute (name, value);
537 if (attr_first == null) {
541 attr_last.NextAttribute = a;
542 a.PreviousAttribute = attr_last;
547 a.Value = XUtil.ToString (value);
551 public override void WriteTo (XmlWriter w)
553 w.WriteStartElement (name.LocalName, name.Namespace.NamespaceName);
555 foreach (XAttribute a in Attributes ()) {
556 if (a.IsNamespaceDeclaration) {
557 if (a.Name.Namespace == XNamespace.Xmlns)
558 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
560 w.WriteAttributeString ("xmlns", a.Value);
563 w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
566 foreach (XNode node in Nodes ())
569 if (explicit_is_empty)
570 w.WriteEndElement ();
572 w.WriteFullEndElement ();
575 public XNamespace GetDefaultNamespace ()
577 for (XElement el = this; el != null; el = el.Parent)
578 foreach (XAttribute a in el.Attributes ())
579 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
580 return XNamespace.Get (a.Value);
581 return XNamespace.None; // nothing is declared.
584 public XNamespace GetNamespaceOfPrefix (string prefix)
586 for (XElement el = this; el != null; el = el.Parent)
587 foreach (XAttribute a in el.Attributes ())
588 if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix)
589 return XNamespace.Get (a.Value);
590 return XNamespace.None; // nothing is declared.
593 public string GetPrefixOfNamespace (XNamespace ns)
595 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
596 if (GetNamespaceOfPrefix (prefix) == ns)
598 return null; // nothing is declared
601 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
603 for (XElement el = this; el != null; el = el.Parent)
604 foreach (XAttribute a in el.Attributes ())
605 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
606 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
609 public void ReplaceAll (object item)
615 public void ReplaceAll (params object [] items)
621 public void ReplaceAttributes (object item)
627 public void ReplaceAttributes (params object [] items)
633 public void SetElementValue (XName name, object value)
635 XElement el = new XElement (name, value);
640 public void SetValue (object value)
642 XNode n = XUtil.ToNode (value);
647 internal override void OnAdded (XNode node, bool addFirst)
649 if (node is XDocument || node is XDocumentType)
650 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", node.GetType ()));
653 void IXmlSerializable.WriteXml (XmlWriter writer)
658 void IXmlSerializable.ReadXml (XmlReader reader)
660 ReadContentFrom (reader, LoadOptions.None);
663 XmlSchema IXmlSerializable.GetSchema ()