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;
52 public XElement (XName name, object value)
54 SetElementValue (name, value);
57 public XElement (XElement source)
60 Add (source.Nodes ());
63 public XElement (XName name)
68 public XElement (XName name, params object [] contents)
75 public XElement (XStreamingElement source)
77 this.name = source.Name;
80 public static explicit operator bool (XElement element)
83 throw new ArgumentNullException ("element");
84 return XmlConvert.ToBoolean (element.Value);
87 public static explicit operator bool? (XElement element)
90 throw new ArgumentNullException ("element");
91 return element.Value == null ? (bool?) null : XmlConvert.ToBoolean (element.Value);
94 public static explicit operator DateTime (XElement element)
97 throw new ArgumentNullException ("element");
98 return XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
101 public static explicit operator DateTime? (XElement element)
104 throw new ArgumentNullException ("element");
105 return element.Value == null ? (DateTime?) null : XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
108 public static explicit operator decimal (XElement element)
111 throw new ArgumentNullException ("element");
112 return XmlConvert.ToDecimal (element.Value);
115 public static explicit operator decimal? (XElement element)
118 throw new ArgumentNullException ("element");
119 return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
122 public static explicit operator double (XElement element)
125 throw new ArgumentNullException ("element");
126 return XmlConvert.ToDouble (element.Value);
129 public static explicit operator double? (XElement element)
132 throw new ArgumentNullException ("element");
133 return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
136 public static explicit operator float (XElement element)
139 throw new ArgumentNullException ("element");
140 return XmlConvert.ToSingle (element.Value);
143 public static explicit operator float? (XElement element)
146 throw new ArgumentNullException ("element");
147 return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
150 public static explicit operator Guid (XElement element)
153 throw new ArgumentNullException ("element");
154 return XmlConvert.ToGuid (element.Value);
157 public static explicit operator Guid? (XElement element)
160 throw new ArgumentNullException ("element");
161 return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
164 public static explicit operator int (XElement element)
167 throw new ArgumentNullException ("element");
168 return XmlConvert.ToInt32 (element.Value);
171 public static explicit operator int? (XElement element)
174 throw new ArgumentNullException ("element");
175 return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
178 public static explicit operator long (XElement element)
181 throw new ArgumentNullException ("element");
182 return XmlConvert.ToInt64 (element.Value);
185 public static explicit operator long? (XElement element)
188 throw new ArgumentNullException ("element");
189 return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
192 [CLSCompliant (false)]
193 public static explicit operator uint (XElement element)
196 throw new ArgumentNullException ("element");
197 return XmlConvert.ToUInt32 (element.Value);
200 [CLSCompliant (false)]
201 public static explicit operator uint? (XElement element)
204 throw new ArgumentNullException ("element");
205 return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
208 [CLSCompliant (false)]
209 public static explicit operator ulong (XElement element)
212 throw new ArgumentNullException ("element");
213 return XmlConvert.ToUInt64 (element.Value);
216 [CLSCompliant (false)]
217 public static explicit operator ulong? (XElement element)
220 throw new ArgumentNullException ("element");
221 return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
224 public static explicit operator TimeSpan (XElement element)
227 throw new ArgumentNullException ("element");
228 return XmlConvert.ToTimeSpan (element.Value);
231 public static explicit operator TimeSpan? (XElement element)
234 throw new ArgumentNullException ("element");
235 return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
238 public static explicit operator string (XElement element)
241 throw new ArgumentNullException ("element");
242 return element.Value;
245 public XAttribute FirstAttribute {
246 get { return attr_first; }
247 internal set { attr_first = value; }
250 public XAttribute LastAttribute {
251 get { return attr_last; }
252 internal set { attr_last = value; }
255 public bool HasAttributes {
256 get { return attr_first != null; }
259 public bool HasElements {
261 foreach (object o in Nodes ())
268 public bool IsEmpty {
269 get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
270 internal set { explicit_is_empty = value; }
277 throw new ArgumentNullException ("value");
282 public override XmlNodeType NodeType {
283 get { return XmlNodeType.Element; }
286 public string Value {
288 StringBuilder sb = null;
289 foreach (object s in Nodes ()) {
291 sb = new StringBuilder ();
294 return sb == null ? String.Empty : sb.ToString ();
302 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
304 List <XElement> list = new List <XElement> ();
307 for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
308 if (name == null || el.Name == name)
313 public XAttribute Attribute (XName name)
315 foreach (XAttribute a in Attributes ())
321 public IEnumerable <XAttribute> Attributes ()
324 for (XAttribute a = attr_first; a != null; a = next) {
325 next = a.NextAttribute;
331 public IEnumerable <XAttribute> Attributes (XName name)
333 foreach (XAttribute a in Attributes ())
338 public static XElement Load (string uri)
340 return Load (uri, LoadOptions.None);
343 public static XElement Load (string uri, LoadOptions options)
345 XmlReaderSettings s = new XmlReaderSettings ();
346 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
347 using (XmlReader r = XmlReader.Create (uri, s)) {
352 public static XElement Load (TextReader tr)
354 return Load (tr, LoadOptions.None);
357 public static XElement Load (TextReader tr, LoadOptions options)
359 XmlReaderSettings s = new XmlReaderSettings ();
360 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
361 using (XmlReader r = XmlReader.Create (tr, s)) {
366 public static XElement Load (XmlReader reader)
368 return Load (reader, LoadOptions.None);
371 public static XElement Load (XmlReader reader, LoadOptions options)
373 XmlReaderSettings s = reader.Settings.Clone ();
374 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
375 using (XmlReader r = XmlReader.Create (reader, s)) {
380 static XElement LoadCore (XmlReader r)
383 if (r.NodeType != XmlNodeType.Element)
384 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
385 XName name = XName.Get (r.LocalName, r.NamespaceURI);
386 XElement e = new XElement (name);
387 if (r.MoveToFirstAttribute ()) {
389 // not sure how current Orcas behavior makes sense here though ...
390 if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
391 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
393 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
394 } while (r.MoveToNextAttribute ());
397 if (!r.IsEmptyElement) {
399 e.ReadContentFrom (r);
402 e.explicit_is_empty = true;
408 public static XElement Parse (string s)
410 return Parse (s, LoadOptions.None);
413 public static XElement Parse (string s, LoadOptions options)
415 return Load (new StringReader (s), options);
418 public void RemoveAll ()
424 public void RemoveAttributes ()
426 while (attr_first != null)
430 public void Save (string filename)
432 Save (filename, SaveOptions.None);
435 public void Save (string filename, SaveOptions options)
437 XmlWriterSettings s = new XmlWriterSettings ();
438 if ((options & SaveOptions.DisableFormatting) != 0) {
441 s.IndentChars = String.Empty;
442 s.NewLineChars = String.Empty;
444 using (XmlWriter w = XmlWriter.Create (filename)) {
449 public void Save (TextWriter tw)
451 Save (tw, SaveOptions.None);
454 public void Save (TextWriter tw, SaveOptions options)
456 XmlWriterSettings s = new XmlWriterSettings ();
457 if ((options & SaveOptions.DisableFormatting) != 0) {
460 s.IndentChars = String.Empty;
461 s.NewLineChars = String.Empty;
463 using (XmlWriter w = XmlWriter.Create (tw)) {
468 public void Save (XmlWriter w)
473 public IEnumerable <XElement> AncestorsAndSelf ()
475 return GetAncestorList (null, true);
478 public IEnumerable <XElement> AncestorsAndSelf (XName name)
480 return GetAncestorList (name, true);
483 public IEnumerable <XElement> DescendantsAndSelf ()
485 List <XElement> list = new List <XElement> ();
487 list.AddRange (Descendants ());
491 public IEnumerable <XElement> DescendantsAndSelf (XName name)
493 List <XElement> list = new List <XElement> ();
494 if (name == this.name)
496 list.AddRange (Descendants (name));
500 public IEnumerable <XNode> DescendantNodesAndSelf ()
503 foreach (XNode node in DescendantNodes ())
507 public void SetAttributeValue (XName name, object value)
509 XAttribute a = Attribute (name);
515 a = new XAttribute (name, value);
517 if (attr_first == null) {
521 attr_last.NextAttribute = a;
522 a.PreviousAttribute = attr_last;
527 a.Value = XUtil.ToString (value);
531 public override void WriteTo (XmlWriter w)
533 w.WriteStartElement (name.LocalName, name.Namespace.NamespaceName);
535 foreach (XAttribute a in Attributes ()) {
536 if (a.IsNamespaceDeclaration) {
537 if (a.Name.Namespace == XNamespace.Xmlns)
538 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
540 w.WriteAttributeString ("xmlns", a.Value);
543 w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
546 foreach (XNode node in Nodes ())
549 if (explicit_is_empty)
550 w.WriteEndElement ();
552 w.WriteFullEndElement ();
555 public XNamespace GetDefaultNamespace ()
557 for (XElement el = this; el != null; el = el.Parent)
558 foreach (XAttribute a in el.Attributes ())
559 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
560 return XNamespace.Get (a.Value);
561 return XNamespace.None; // nothing is declared.
564 public XNamespace GetNamespaceOfPrefix (string prefix)
566 for (XElement el = this; el != null; el = el.Parent)
567 foreach (XAttribute a in el.Attributes ())
568 if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix)
569 return XNamespace.Get (a.Value);
570 return XNamespace.None; // nothing is declared.
573 public string GetPrefixOfNamespace (XNamespace ns)
575 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
576 if (GetNamespaceOfPrefix (prefix) == ns)
578 return null; // nothing is declared
581 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
583 for (XElement el = this; el != null; el = el.Parent)
584 foreach (XAttribute a in el.Attributes ())
585 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
586 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
589 public void ReplaceAll (object item)
595 public void ReplaceAll (params object [] items)
601 public void ReplaceAttributes (object item)
607 public void ReplaceAttributes (params object [] items)
613 public void SetElementValue (XName name, object value)
615 XElement el = new XElement (name, value);
620 public void SetValue (object value)
622 XNode n = XUtil.ToNode (value);
627 internal override void OnAdded (XNode node, bool addFirst)
629 if (node is XDocument || node is XDocumentType)
630 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", node.GetType ()));
633 void IXmlSerializable.WriteXml (XmlWriter writer)
638 void IXmlSerializable.ReadXml (XmlReader reader)
640 ReadContentFrom (reader);
643 XmlSchema IXmlSerializable.GetSchema ()