5 // Kral Ferch <kral_ferch@hotmail.com>
6 // Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
9 // (C) 2002 Atsushi Enomoto
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.Collections;
35 using System.Globalization;
38 using System.Xml.XPath;
40 using System.Diagnostics;
41 using System.Xml.Schema;
46 public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
48 static EmptyNodeList emptyList = new EmptyNodeList ();
50 class EmptyNodeList : XmlNodeList
52 static IEnumerator emptyEnumerator = new object [0].GetEnumerator ();
54 public override int Count {
58 public override IEnumerator GetEnumerator ()
60 return emptyEnumerator;
63 public override XmlNode Item (int index)
71 XmlDocument ownerDocument;
73 XmlNodeListChildren childNodes;
79 internal XmlNode (XmlDocument ownerDocument)
81 this.ownerDocument = ownerDocument;
88 public virtual XmlAttributeCollection Attributes {
92 public virtual string BaseURI {
94 // Isn't it conformant to W3C XML Base Recommendation?
95 // As far as I tested, there are not...
96 return (ParentNode != null) ? ParentNode.ChildrenBaseURI : String.Empty;
100 internal virtual string ChildrenBaseURI {
106 public virtual XmlNodeList ChildNodes {
108 IHasXmlChildNode l = this as IHasXmlChildNode;
111 if (childNodes == null)
112 childNodes = new XmlNodeListChildren (l);
117 public virtual XmlNode FirstChild {
119 IHasXmlChildNode l = this as IHasXmlChildNode;
120 XmlLinkedNode c = (l == null) ?
121 null : l.LastLinkedChild;
122 return c == null ? null : c.NextLinkedSibling;
126 public virtual bool HasChildNodes {
127 get { return LastChild != null; }
130 public virtual string InnerText {
133 case XmlNodeType.Text:
134 case XmlNodeType.CDATA:
135 case XmlNodeType.SignificantWhitespace:
136 case XmlNodeType.Whitespace:
139 if (FirstChild == null)
141 if (FirstChild == LastChild)
142 return FirstChild.NodeType != XmlNodeType.Comment ?
143 FirstChild.InnerText :
146 StringBuilder builder = null;
147 AppendChildValues (ref builder);
148 return builder == null ? String.Empty : builder.ToString ();
152 if (! (this is XmlDocumentFragment))
153 throw new InvalidOperationException ("This node is read only. Cannot be modified.");
155 AppendChild (OwnerDocument.CreateTextNode (value));
159 private void AppendChildValues (ref StringBuilder builder)
161 XmlNode node = FirstChild;
163 while (node != null) {
164 switch (node.NodeType) {
165 case XmlNodeType.Text:
166 case XmlNodeType.CDATA:
167 case XmlNodeType.SignificantWhitespace:
168 case XmlNodeType.Whitespace:
170 builder = new StringBuilder ();
171 builder.Append (node.Value);
174 node.AppendChildValues (ref builder);
175 node = node.NextSibling;
179 public virtual string InnerXml {
181 StringWriter sw = new StringWriter ();
182 XmlTextWriter xtw = new XmlTextWriter (sw);
184 WriteContentTo (xtw);
186 return sw.GetStringBuilder ().ToString ();
190 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
194 public virtual bool IsReadOnly {
197 XmlNode curNode = this;
200 switch (curNode.NodeType)
202 case XmlNodeType.EntityReference:
203 case XmlNodeType.Entity:
206 case XmlNodeType.Attribute:
207 curNode = ((XmlAttribute)curNode).OwnerElement;
211 curNode = curNode.ParentNode;
215 while (curNode != null) ;
221 [System.Runtime.CompilerServices.IndexerName("Item")]
222 public virtual XmlElement this [string name] {
224 for (int i = 0; i < ChildNodes.Count; i++) {
225 XmlNode node = ChildNodes [i];
226 if ((node.NodeType == XmlNodeType.Element) &&
227 (node.Name == name)) {
228 return (XmlElement) node;
236 [System.Runtime.CompilerServices.IndexerName("Item")]
237 public virtual XmlElement this [string localname, string ns] {
239 for (int i = 0; i < ChildNodes.Count; i++) {
240 XmlNode node = ChildNodes [i];
241 if ((node.NodeType == XmlNodeType.Element) &&
242 (node.LocalName == localname) &&
243 (node.NamespaceURI == ns)) {
244 return (XmlElement) node;
252 public virtual XmlNode LastChild {
254 IHasXmlChildNode l = this as IHasXmlChildNode;
255 return l == null ? null : l.LastLinkedChild;
259 public abstract string LocalName { get; }
261 public abstract string Name { get; }
263 public virtual string NamespaceURI {
264 get { return String.Empty; }
267 public virtual XmlNode NextSibling {
271 public abstract XmlNodeType NodeType { get; }
273 internal virtual XPathNodeType XPathNodeType {
275 throw new InvalidOperationException ("Can not get XPath node type from " + this.GetType ().ToString ());
279 public virtual string OuterXml {
281 StringWriter sw = new StringWriter ();
282 XmlTextWriter xtw = new XmlTextWriter (sw);
286 return sw.ToString ();
290 public virtual XmlDocument OwnerDocument {
291 get { return ownerDocument; }
294 public virtual XmlNode ParentNode {
295 get { return parentNode; }
298 public virtual string Prefix {
299 get { return String.Empty; }
303 public virtual XmlNode PreviousSibling {
307 public virtual string Value {
309 set { throw new InvalidOperationException ("This node does not have a value"); }
312 internal virtual string XmlLang {
314 if(Attributes != null)
315 for (int i = 0; i < Attributes.Count; i++) {
316 XmlAttribute attr = Attributes [i];
317 if(attr.Name == "xml:lang")
320 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
324 internal virtual XmlSpace XmlSpace {
326 if(Attributes != null) {
327 for (int i = 0; i < Attributes.Count; i++) {
328 XmlAttribute attr = Attributes [i];
329 if(attr.Name == "xml:space") {
331 case "preserve": return XmlSpace.Preserve;
332 case "default": return XmlSpace.Default;
338 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
343 public virtual IXmlSchemaInfo SchemaInfo {
353 public virtual XmlNode AppendChild (XmlNode newChild)
355 // AppendChild(n) is equivalent to InsertBefore(n, null)
356 return InsertBefore (newChild, null);
359 internal XmlNode AppendChild (XmlNode newChild, bool checkNodeType)
361 return InsertBefore (newChild, null, checkNodeType, true);
364 public virtual XmlNode Clone ()
366 // By MS document, it is equivalent to CloneNode(true).
367 return this.CloneNode (true);
370 public abstract XmlNode CloneNode (bool deep);
373 public virtual XPathNavigator CreateNavigator ()
375 // XmlDocument has overriden definition, so it is safe
376 // to use OwnerDocument here.
377 return OwnerDocument.CreateNavigator (this);
380 public XPathNavigator CreateNavigator ()
382 XmlDocument document = this.NodeType == XmlNodeType.Document ?
383 this as XmlDocument : this.ownerDocument;
384 return document.CreateNavigator (this);
388 public IEnumerator GetEnumerator ()
390 return ChildNodes.GetEnumerator ();
393 public virtual string GetNamespaceOfPrefix (string prefix)
397 throw new ArgumentNullException ("prefix");
400 return XmlNamespaceManager.XmlnsXml;
402 return XmlNamespaceManager.XmlnsXmlns;
408 case XmlNodeType.Attribute:
409 node = ((XmlAttribute) this).OwnerElement;
413 case XmlNodeType.Element:
421 while (node != null) {
422 if (node.Prefix == prefix)
423 return node.NamespaceURI;
424 if (node.NodeType == XmlNodeType.Element &&
425 ((XmlElement) node).HasAttributes) {
426 int count = node.Attributes.Count;
427 for (int i = 0; i < count; i++) {
428 XmlAttribute attr = node.Attributes [i];
429 if (prefix == attr.LocalName && attr.Prefix == "xmlns"
430 || attr.Name == "xmlns" && prefix == String.Empty)
434 node = node.ParentNode;
439 public virtual string GetPrefixOfNamespace (string namespaceURI)
442 switch (namespaceURI) {
443 case XmlNamespaceManager.XmlnsXml:
444 return XmlNamespaceManager.PrefixXml;
445 case XmlNamespaceManager.XmlnsXmlns:
446 return XmlNamespaceManager.PrefixXmlns;
452 case XmlNodeType.Attribute:
453 node = ((XmlAttribute) this).OwnerElement;
455 case XmlNodeType.Element:
463 while (node != null) {
464 if (node.NodeType == XmlNodeType.Element &&
465 ((XmlElement) node).HasAttributes) {
466 for (int i = 0; i < node.Attributes.Count; i++) {
467 XmlAttribute attr = node.Attributes [i];
468 if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
469 return attr.LocalName;
470 else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
474 node = node.ParentNode;
479 object ICloneable.Clone ()
484 IEnumerator IEnumerable.GetEnumerator ()
486 return GetEnumerator ();
489 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
491 // InsertAfter(n1, n2) is equivalent to InsertBefore(n1, n2.PreviousSibling).
493 // I took this way because current implementation
494 // Calling InsertBefore() in this method is faster than
495 // the counterpart, since NextSibling is faster than
496 // PreviousSibling (these children are forward-only list).
497 XmlNode argNode = null;
498 if (refChild != null)
499 argNode = refChild.NextSibling;
500 else if (FirstChild != null)
501 argNode = FirstChild;
502 return InsertBefore (newChild, argNode);
505 public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
507 return InsertBefore (newChild, refChild, true, true);
510 // check for the node to be one of node ancestors
511 internal bool IsAncestor (XmlNode newChild)
513 XmlNode currNode = this.ParentNode;
514 while(currNode != null)
516 if(currNode == newChild)
518 currNode = currNode.ParentNode;
523 internal XmlNode InsertBefore (XmlNode newChild, XmlNode refChild, bool checkNodeType, bool raiseEvent)
526 CheckNodeInsertion (newChild, refChild);
528 if (newChild == refChild)
531 IHasXmlChildNode l = (IHasXmlChildNode) this;
533 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
536 ownerDoc.onNodeInserting (newChild, this);
538 if (newChild.ParentNode != null)
539 newChild.ParentNode.RemoveChild (newChild, checkNodeType);
541 if (newChild.NodeType == XmlNodeType.DocumentFragment) {
542 // This recursively invokes events. (It is compatible with MS implementation.)
543 while (newChild.FirstChild != null)
544 this.InsertBefore (newChild.FirstChild, refChild);
547 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
548 newLinkedChild.parentNode = this;
550 if (refChild == null) {
551 // newChild is the last child:
552 // * set newChild as NextSibling of the existing lastchild
553 // * set LastChild = newChild
554 // * set NextSibling of newChild as FirstChild
555 if (l.LastLinkedChild != null) {
556 XmlLinkedNode formerFirst = (XmlLinkedNode) FirstChild;
557 l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
558 l.LastLinkedChild = newLinkedChild;
559 newLinkedChild.NextLinkedSibling = formerFirst;
561 l.LastLinkedChild = newLinkedChild;
562 l.LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
565 // newChild is not the last child:
566 // * if newchild is first, then set next of lastchild is newChild.
567 // otherwise, set next of previous sibling to newChild
568 // * set next of newChild to refChild
569 XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
571 l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
573 prev.NextLinkedSibling = newLinkedChild;
574 newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
576 switch (newChild.NodeType) {
577 case XmlNodeType.EntityReference:
578 ((XmlEntityReference) newChild).SetReferencedEntityContent ();
580 case XmlNodeType.Entity:
582 case XmlNodeType.DocumentType:
587 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
592 private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
594 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
596 if (NodeType != XmlNodeType.Element &&
597 NodeType != XmlNodeType.Attribute &&
598 NodeType != XmlNodeType.Document &&
599 NodeType != XmlNodeType.DocumentFragment)
600 throw new InvalidOperationException (String.Format ("Node cannot be appended to current node {0}.", NodeType));
603 case XmlNodeType.Attribute:
604 switch (newChild.NodeType) {
605 case XmlNodeType.Text:
606 case XmlNodeType.EntityReference:
609 throw new InvalidOperationException (String.Format (
610 "Cannot insert specified type of node {0} as a child of this node {1}.",
611 newChild.NodeType, NodeType));
614 case XmlNodeType.Element:
615 switch (newChild.NodeType) {
616 case XmlNodeType.Attribute:
617 case XmlNodeType.Document:
618 case XmlNodeType.DocumentType:
619 case XmlNodeType.Entity:
620 case XmlNodeType.Notation:
621 case XmlNodeType.XmlDeclaration:
622 throw new InvalidOperationException ("Cannot insert specified type of node as a child of this node.");
628 throw new InvalidOperationException ("The node is readonly.");
630 if (newChild.OwnerDocument != ownerDoc)
631 throw new ArgumentException ("Can't append a node created by another document.");
633 if (refChild != null) {
634 if (refChild.ParentNode != this)
635 throw new ArgumentException ("The reference node is not a child of this node.");
638 if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement) && newChild != ownerDoc.DocumentElement)
639 throw new XmlException ("multiple document element not allowed.");
641 // checking validity finished. then appending...
644 if (newChild == this || IsAncestor (newChild))
645 throw new ArgumentException("Cannot insert a node or any ancestor of that node as a child of itself.");
649 public virtual void Normalize ()
651 StringBuilder tmpBuilder = new StringBuilder ();
652 int count = this.ChildNodes.Count;
654 for (int i = 0; i < count; i++) {
655 XmlNode c = ChildNodes [i];
656 switch (c.NodeType) {
657 case XmlNodeType.Text:
658 case XmlNodeType.Whitespace:
659 case XmlNodeType.SignificantWhitespace:
660 tmpBuilder.Append (c.Value);
664 NormalizeRange (start, i, tmpBuilder);
665 // Continue to normalize from next node.
671 NormalizeRange (start, count, tmpBuilder);
675 private void NormalizeRange (int start, int i, StringBuilder tmpBuilder)
678 // If Texts and Whitespaces are mixed, Text takes precedence to remain.
679 // i.e. Whitespace should be removed.
680 for (int j = start; j < i; j++) {
681 XmlNode keep = ChildNodes [j];
682 if (keep.NodeType == XmlNodeType.Text) {
686 else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
688 // but don't break up to find Text nodes.
692 for (int del = start; del < keepPos; del++)
693 RemoveChild (ChildNodes [start]);
694 int rest = i - keepPos - 1;
695 for (int del = 0; del < rest; del++) {
696 RemoveChild (ChildNodes [start + 1]);
701 ChildNodes [start].Value = tmpBuilder.ToString ();
702 // otherwise nothing to be normalized
704 tmpBuilder.Length = 0;
707 public virtual XmlNode PrependChild (XmlNode newChild)
709 return InsertAfter (newChild, null);
712 public virtual void RemoveAll ()
714 if (Attributes != null)
715 Attributes.RemoveAll ();
717 for (XmlNode node = FirstChild; node != null; node = next) {
718 next = node.NextSibling;
723 public virtual XmlNode RemoveChild (XmlNode oldChild)
725 return RemoveChild (oldChild, true);
728 private void CheckNodeRemoval ()
730 if (NodeType != XmlNodeType.Attribute &&
731 NodeType != XmlNodeType.Element &&
732 NodeType != XmlNodeType.Document &&
733 NodeType != XmlNodeType.DocumentFragment)
734 throw new ArgumentException (String.Format ("This {0} node cannot remove its child.", NodeType));
737 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
740 internal XmlNode RemoveChild (XmlNode oldChild, bool checkNodeType)
742 if (oldChild == null)
743 throw new NullReferenceException ();
744 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
745 if(oldChild.ParentNode != this)
746 throw new ArgumentException ("The node to be removed is not a child of this node.");
749 ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
754 IHasXmlChildNode l = (IHasXmlChildNode) this;
756 if (Object.ReferenceEquals (l.LastLinkedChild, l.LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (l.LastLinkedChild, oldChild))
757 // If there is only one children, simply clear.
758 l.LastLinkedChild = null;
760 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
761 XmlLinkedNode beforeLinkedChild = l.LastLinkedChild;
762 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
764 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, l.LastLinkedChild) == false &&
765 Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
766 beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
768 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
769 throw new ArgumentException ();
771 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
773 // Each derived class may have its own l.LastLinkedChild, so we must set it explicitly.
774 if (oldLinkedChild.NextLinkedSibling == firstChild)
775 l.LastLinkedChild = beforeLinkedChild;
777 oldLinkedChild.NextLinkedSibling = null;
781 ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
782 oldChild.parentNode = null; // clear parent 'after' above logic.
787 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
789 if(oldChild.ParentNode != this)
790 throw new ArgumentException ("The node to be removed is not a child of this node.");
792 if (newChild == this || IsAncestor (newChild))
793 throw new InvalidOperationException("Cannot insert a node or any ancestor of that node as a child of itself.");
795 XmlNode next = oldChild.NextSibling;
796 RemoveChild (oldChild);
797 InsertBefore (newChild, next);
801 // WARNING: don't use this member outside XmlAttribute nodes.
802 internal XmlElement AttributeOwnerElement {
803 get { return (XmlElement) parentNode; }
804 set { parentNode = value; }
807 internal void SearchDescendantElements (string name, bool matchAll, ArrayList list)
809 for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
810 if (n.NodeType != XmlNodeType.Element)
812 if (matchAll || n.Name == name)
814 n.SearchDescendantElements (name, matchAll, list);
818 internal void SearchDescendantElements (string name, bool matchAllName, string ns, bool matchAllNS, ArrayList list)
820 for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
821 if (n.NodeType != XmlNodeType.Element)
823 if ((matchAllName || n.LocalName == name)
824 && (matchAllNS || n.NamespaceURI == ns))
826 n.SearchDescendantElements (name, matchAllName, ns, matchAllNS, list);
830 public XmlNodeList SelectNodes (string xpath)
832 return SelectNodes (xpath, null);
835 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
837 XPathNavigator nav = CreateNavigator ();
838 XPathExpression expr = nav.Compile (xpath);
840 expr.SetContext (nsmgr);
841 XPathNodeIterator iter = nav.Select (expr);
843 ArrayList rgNodes = new ArrayList ();
844 while (iter.MoveNext ())
846 rgNodes.Add (((IHasXmlNode) iter.Current).GetNode ());
848 return new XmlNodeArrayList (rgNodes);
850 return new XmlIteratorNodeList (iter);
853 public XmlNode SelectSingleNode (string xpath)
855 return SelectSingleNode (xpath, null);
858 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
860 XPathNavigator nav = CreateNavigator ();
861 XPathExpression expr = nav.Compile (xpath);
863 expr.SetContext (nsmgr);
864 XPathNodeIterator iter = nav.Select (expr);
865 if (!iter.MoveNext ())
867 return ((IHasXmlNode) iter.Current).GetNode ();
870 public virtual bool Supports (string feature, string version)
872 if (String.Compare (feature, "xml", true, CultureInfo.InvariantCulture) == 0 // not case-sensitive
873 && (String.Compare (version, "1.0", true, CultureInfo.InvariantCulture) == 0
874 || String.Compare (version, "2.0", true, CultureInfo.InvariantCulture) == 0))
880 public abstract void WriteContentTo (XmlWriter w);
882 public abstract void WriteTo (XmlWriter w);
884 // It parses this and all the ancestor elements,
885 // find 'xmlns' declarations, stores and then return them.
886 internal XmlNamespaceManager ConstructNamespaceManager ()
888 XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
889 XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
890 XmlElement el = null;
891 switch(this.NodeType) {
892 case XmlNodeType.Attribute:
893 el = ((XmlAttribute)this).OwnerElement;
895 case XmlNodeType.Element:
896 el = this as XmlElement;
899 el = this.ParentNode as XmlElement;
904 for (int i = 0; i < el.Attributes.Count; i++) {
905 XmlAttribute attr = el.Attributes [i];
906 if(attr.Prefix == "xmlns") {
907 if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
908 nsmgr.AddNamespace (attr.LocalName, attr.Value);
909 } else if(attr.Name == "xmlns") {
910 if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
911 nsmgr.AddNamespace (String.Empty, attr.Value);
914 // When reached to document, then it will set null value :)
915 el = el.ParentNode as XmlElement;