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 XmlConvert.ToBoolean (element.Value);
89 public static explicit operator bool? (XElement element)
94 return element.Value == null ? (bool?) null : XmlConvert.ToBoolean (element.Value);
97 public static explicit operator DateTime (XElement element)
100 throw new ArgumentNullException ("element");
101 return XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
104 public static explicit operator DateTime? (XElement element)
109 return element.Value == null ? (DateTime?) null : XmlConvert.ToDateTime (element.Value, XmlDateTimeSerializationMode.RoundtripKind);
112 public static explicit operator decimal (XElement element)
115 throw new ArgumentNullException ("element");
116 return XmlConvert.ToDecimal (element.Value);
119 public static explicit operator decimal? (XElement element)
124 return element.Value == null ? (decimal?) null : XmlConvert.ToDecimal (element.Value);
127 public static explicit operator double (XElement element)
130 throw new ArgumentNullException ("element");
131 return XmlConvert.ToDouble (element.Value);
134 public static explicit operator double? (XElement element)
139 return element.Value == null ? (double?) null : XmlConvert.ToDouble (element.Value);
142 public static explicit operator float (XElement element)
145 throw new ArgumentNullException ("element");
146 return XmlConvert.ToSingle (element.Value);
149 public static explicit operator float? (XElement element)
154 return element.Value == null ? (float?) null : XmlConvert.ToSingle (element.Value);
157 public static explicit operator Guid (XElement element)
160 throw new ArgumentNullException ("element");
161 return XmlConvert.ToGuid (element.Value);
164 public static explicit operator Guid? (XElement element)
169 return element.Value == null ? (Guid?) null : XmlConvert.ToGuid (element.Value);
172 public static explicit operator int (XElement element)
175 throw new ArgumentNullException ("element");
176 return XmlConvert.ToInt32 (element.Value);
179 public static explicit operator int? (XElement element)
184 return element.Value == null ? (int?) null : XmlConvert.ToInt32 (element.Value);
187 public static explicit operator long (XElement element)
190 throw new ArgumentNullException ("element");
191 return XmlConvert.ToInt64 (element.Value);
194 public static explicit operator long? (XElement element)
199 return element.Value == null ? (long?) null : XmlConvert.ToInt64 (element.Value);
202 [CLSCompliant (false)]
203 public static explicit operator uint (XElement element)
206 throw new ArgumentNullException ("element");
207 return XmlConvert.ToUInt32 (element.Value);
210 [CLSCompliant (false)]
211 public static explicit operator uint? (XElement element)
216 return element.Value == null ? (uint?) null : XmlConvert.ToUInt32 (element.Value);
219 [CLSCompliant (false)]
220 public static explicit operator ulong (XElement element)
223 throw new ArgumentNullException ("element");
224 return XmlConvert.ToUInt64 (element.Value);
227 [CLSCompliant (false)]
228 public static explicit operator ulong? (XElement element)
233 return element.Value == null ? (ulong?) null : XmlConvert.ToUInt64 (element.Value);
236 public static explicit operator TimeSpan (XElement element)
239 throw new ArgumentNullException ("element");
240 return XmlConvert.ToTimeSpan (element.Value);
243 public static explicit operator TimeSpan? (XElement element)
248 return element.Value == null ? (TimeSpan?) null : XmlConvert.ToTimeSpan (element.Value);
251 public static explicit operator string (XElement element)
256 return element.Value;
259 public XAttribute FirstAttribute {
260 get { return attr_first; }
261 internal set { attr_first = value; }
264 public XAttribute LastAttribute {
265 get { return attr_last; }
266 internal set { attr_last = value; }
269 public bool HasAttributes {
270 get { return attr_first != null; }
273 public bool HasElements {
275 foreach (object o in Nodes ())
282 public bool IsEmpty {
283 get { return !Nodes ().GetEnumerator ().MoveNext () && explicit_is_empty; }
284 internal set { explicit_is_empty = value; }
291 throw new ArgumentNullException ("value");
296 public override XmlNodeType NodeType {
297 get { return XmlNodeType.Element; }
300 public string Value {
302 StringBuilder sb = null;
303 foreach (XNode n in Nodes ()) {
305 sb = new StringBuilder ();
307 sb.Append (((XText) n).Value);
308 else if (n is XElement)
309 sb.Append (((XElement) n).Value);
311 return sb == null ? String.Empty : sb.ToString ();
319 IEnumerable <XElement> GetAncestorList (XName name, bool getMeIn)
321 List <XElement> list = new List <XElement> ();
324 for (XElement el = Parent as XElement; el != null; el = el.Parent as XElement)
325 if (name == null || el.Name == name)
330 public XAttribute Attribute (XName name)
332 foreach (XAttribute a in Attributes ())
338 public IEnumerable <XAttribute> Attributes ()
341 for (XAttribute a = attr_first; a != null; a = next) {
342 next = a.NextAttribute;
348 public IEnumerable <XAttribute> Attributes (XName name)
350 foreach (XAttribute a in Attributes ())
355 public static XElement Load (string uri)
357 return Load (uri, LoadOptions.None);
360 public static XElement Load (string uri, LoadOptions options)
362 XmlReaderSettings s = new XmlReaderSettings ();
363 s.ProhibitDtd = false;
364 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
365 using (XmlReader r = XmlReader.Create (uri, s)) {
366 return LoadCore (r, options);
370 public static XElement Load (TextReader tr)
372 return Load (tr, LoadOptions.None);
375 public static XElement Load (TextReader tr, LoadOptions options)
377 XmlReaderSettings s = new XmlReaderSettings ();
378 s.ProhibitDtd = false;
379 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
380 using (XmlReader r = XmlReader.Create (tr, s)) {
381 return LoadCore (r, options);
385 public static XElement Load (XmlReader reader)
387 return Load (reader, LoadOptions.None);
390 public static XElement Load (XmlReader reader, LoadOptions options)
392 XmlReaderSettings s = reader.Settings.Clone ();
393 s.ProhibitDtd = false;
394 s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
395 using (XmlReader r = XmlReader.Create (reader, s)) {
396 return LoadCore (r, options);
400 internal static XElement LoadCore (XmlReader r, LoadOptions options)
403 if (r.NodeType != XmlNodeType.Element)
404 throw new InvalidOperationException ("The XmlReader must be positioned at an element");
405 XName name = XName.Get (r.LocalName, r.NamespaceURI);
406 XElement e = new XElement (name);
407 e.FillLineInfoAndBaseUri (r, options);
409 if (r.MoveToFirstAttribute ()) {
411 // not sure how current Orcas behavior makes sense here though ...
412 if (r.LocalName == "xmlns" && r.NamespaceURI == XNamespace.Xmlns.NamespaceName)
413 e.SetAttributeValue (XNamespace.None.GetName ("xmlns"), r.Value);
415 e.SetAttributeValue (XName.Get (r.LocalName, r.NamespaceURI), r.Value);
416 e.LastAttribute.FillLineInfoAndBaseUri (r, options);
417 } while (r.MoveToNextAttribute ());
420 if (!r.IsEmptyElement) {
422 e.ReadContentFrom (r, options);
424 e.explicit_is_empty = false;
426 e.explicit_is_empty = true;
432 public static XElement Parse (string s)
434 return Parse (s, LoadOptions.None);
437 public static XElement Parse (string s, LoadOptions options)
439 return Load (new StringReader (s), options);
442 public void RemoveAll ()
448 public void RemoveAttributes ()
450 while (attr_first != null)
454 public void Save (string filename)
456 Save (filename, SaveOptions.None);
459 public void Save (string filename, SaveOptions options)
461 XmlWriterSettings s = new XmlWriterSettings ();
462 s.Indent = options != SaveOptions.DisableFormatting;
463 using (XmlWriter w = XmlWriter.Create (filename, s)) {
468 public void Save (TextWriter tw)
470 Save (tw, SaveOptions.None);
473 public void Save (TextWriter tw, SaveOptions options)
475 XmlWriterSettings s = new XmlWriterSettings ();
476 s.Indent = options != SaveOptions.DisableFormatting;
477 using (XmlWriter w = XmlWriter.Create (tw, s)) {
482 public void Save (XmlWriter w)
487 public IEnumerable <XElement> AncestorsAndSelf ()
489 return GetAncestorList (null, true);
492 public IEnumerable <XElement> AncestorsAndSelf (XName name)
494 return GetAncestorList (name, true);
497 public IEnumerable <XElement> DescendantsAndSelf ()
499 List <XElement> list = new List <XElement> ();
501 list.AddRange (Descendants ());
505 public IEnumerable <XElement> DescendantsAndSelf (XName name)
507 List <XElement> list = new List <XElement> ();
508 if (name == this.name)
510 list.AddRange (Descendants (name));
514 public IEnumerable <XNode> DescendantNodesAndSelf ()
517 foreach (XNode node in DescendantNodes ())
521 public void SetAttributeValue (XName name, object value)
523 XAttribute a = Attribute (name);
529 SetAttributeObject (new XAttribute (name, value));
532 a.Value = XUtil.ToString (value);
536 void SetAttributeObject (XAttribute a)
538 a = (XAttribute) XUtil.GetDetachedObject (a);
540 if (attr_first == null) {
544 attr_last.NextAttribute = a;
545 a.PreviousAttribute = attr_last;
550 public override void WriteTo (XmlWriter w)
552 // some people expect the same prefix output as in input,
553 // in the loss of performance... see bug #466423.
554 string prefix = name.NamespaceName.Length > 0 ? w.LookupPrefix (name.Namespace.NamespaceName) : String.Empty;
555 foreach (XAttribute a in Attributes ()) {
556 if (a.IsNamespaceDeclaration && a.Value == name.Namespace.NamespaceName) {
557 if (a.Name.Namespace == XNamespace.Xmlns)
558 prefix = a.Name.LocalName;
559 // otherwise xmlns="..."
564 w.WriteStartElement (prefix, name.LocalName, name.Namespace.NamespaceName);
566 foreach (XAttribute a in Attributes ()) {
567 if (a.IsNamespaceDeclaration) {
568 if (a.Name.Namespace == XNamespace.Xmlns)
569 w.WriteAttributeString ("xmlns", a.Name.LocalName, XNamespace.Xmlns.NamespaceName, a.Value);
571 w.WriteAttributeString ("xmlns", a.Value);
574 w.WriteAttributeString (a.Name.LocalName, a.Name.Namespace.NamespaceName, a.Value);
577 foreach (XNode node in Nodes ())
580 if (explicit_is_empty)
581 w.WriteEndElement ();
583 w.WriteFullEndElement ();
586 public XNamespace GetDefaultNamespace ()
588 for (XElement el = this; el != null; el = el.Parent)
589 foreach (XAttribute a in el.Attributes ())
590 if (a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
591 return XNamespace.Get (a.Value);
592 return XNamespace.None; // nothing is declared.
595 public XNamespace GetNamespaceOfPrefix (string prefix)
597 for (XElement el = this; el != null; el = el.Parent)
598 foreach (XAttribute a in el.Attributes ())
599 if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix)
600 return XNamespace.Get (a.Value);
601 return XNamespace.None; // nothing is declared.
604 public string GetPrefixOfNamespace (XNamespace ns)
606 foreach (string prefix in GetPrefixOfNamespaceCore (ns))
607 if (GetNamespaceOfPrefix (prefix) == ns)
609 return null; // nothing is declared
612 IEnumerable<string> GetPrefixOfNamespaceCore (XNamespace ns)
614 for (XElement el = this; el != null; el = el.Parent)
615 foreach (XAttribute a in el.Attributes ())
616 if (a.IsNamespaceDeclaration && a.Value == ns.NamespaceName)
617 yield return a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName;
620 public void ReplaceAll (object item)
626 public void ReplaceAll (params object [] items)
632 public void ReplaceAttributes (object item)
638 public void ReplaceAttributes (params object [] items)
644 public void SetElementValue (XName name, object value)
646 XElement el = new XElement (name, value);
651 public void SetValue (object value)
654 throw new ArgumentNullException ("value");
655 if (value is XAttribute || value is XDocument || value is XDeclaration || value is XDocumentType)
656 throw new ArgumentException (String.Format ("Node type {0} is not allowed as element value", value.GetType ()));
658 foreach (object o in XUtil.ExpandArray (value))
662 internal override bool OnAddingObject (object o, bool rejectAttribute, XNode refNode, bool addFirst)
664 if (o is XDocument || o is XDocumentType || o is XDeclaration || (rejectAttribute && o is XAttribute))
665 throw new ArgumentException (String.Format ("A node of type {0} cannot be added as a content", o.GetType ()));
667 XAttribute a = o as XAttribute;
669 foreach (XAttribute ia in Attributes ())
670 if (a.Name == ia.Name)
671 throw new InvalidOperationException (String.Format ("Duplicate attribute: {0}", a.Name));
672 SetAttributeObject (a);
675 else if (o is string && refNode is XText) {
676 ((XText) refNode).Value += o as string;
683 void IXmlSerializable.WriteXml (XmlWriter writer)
688 void IXmlSerializable.ReadXml (XmlReader reader)
690 ReadContentFrom (reader, LoadOptions.None);
693 XmlSchema IXmlSerializable.GetSchema ()