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:
140 if (FirstChild == null)
142 if (FirstChild == LastChild)
143 return FirstChild.NodeType != XmlNodeType.Comment ?
144 FirstChild.InnerText :
147 StringBuilder builder = null;
148 AppendChildValues (ref builder);
149 return builder == null ? String.Empty : builder.ToString ();
153 if (! (this is XmlDocumentFragment))
154 throw new InvalidOperationException ("This node is read only. Cannot be modified.");
156 AppendChild (OwnerDocument.CreateTextNode (value));
160 private void AppendChildValues (ref StringBuilder builder)
162 XmlNode node = FirstChild;
164 while (node != null) {
165 switch (node.NodeType) {
166 case XmlNodeType.Text:
167 case XmlNodeType.CDATA:
168 case XmlNodeType.SignificantWhitespace:
169 case XmlNodeType.Whitespace:
171 builder = new StringBuilder ();
172 builder.Append (node.Value);
175 node.AppendChildValues (ref builder);
176 node = node.NextSibling;
180 public virtual string InnerXml {
182 StringWriter sw = new StringWriter ();
183 XmlTextWriter xtw = new XmlTextWriter (sw);
185 WriteContentTo (xtw);
187 return sw.GetStringBuilder ().ToString ();
191 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
195 public virtual bool IsReadOnly {
198 XmlNode curNode = this;
201 switch (curNode.NodeType)
203 case XmlNodeType.EntityReference:
204 case XmlNodeType.Entity:
207 case XmlNodeType.Attribute:
208 curNode = ((XmlAttribute)curNode).OwnerElement;
212 curNode = curNode.ParentNode;
216 while (curNode != null) ;
222 [System.Runtime.CompilerServices.IndexerName("Item")]
223 public virtual XmlElement this [string name] {
225 for (int i = 0; i < ChildNodes.Count; i++) {
226 XmlNode node = ChildNodes [i];
227 if ((node.NodeType == XmlNodeType.Element) &&
228 (node.Name == name)) {
229 return (XmlElement) node;
237 [System.Runtime.CompilerServices.IndexerName("Item")]
238 public virtual XmlElement this [string localname, string ns] {
240 for (int i = 0; i < ChildNodes.Count; i++) {
241 XmlNode node = ChildNodes [i];
242 if ((node.NodeType == XmlNodeType.Element) &&
243 (node.LocalName == localname) &&
244 (node.NamespaceURI == ns)) {
245 return (XmlElement) node;
253 public virtual XmlNode LastChild {
255 IHasXmlChildNode l = this as IHasXmlChildNode;
256 return l == null ? null : l.LastLinkedChild;
260 public abstract string LocalName { get; }
262 public abstract string Name { get; }
264 public virtual string NamespaceURI {
265 get { return String.Empty; }
268 public virtual XmlNode NextSibling {
272 public abstract XmlNodeType NodeType { get; }
274 internal virtual XPathNodeType XPathNodeType {
276 throw new InvalidOperationException ("Can not get XPath node type from " + this.GetType ().ToString ());
280 public virtual string OuterXml {
282 StringWriter sw = new StringWriter ();
283 XmlTextWriter xtw = new XmlTextWriter (sw);
287 return sw.ToString ();
291 public virtual XmlDocument OwnerDocument {
292 get { return ownerDocument; }
295 public virtual XmlNode ParentNode {
296 get { return parentNode; }
299 public virtual string Prefix {
300 get { return String.Empty; }
304 public virtual XmlNode PreviousSibling {
308 public virtual string Value {
310 set { throw new InvalidOperationException ("This node does not have a value"); }
313 internal virtual string XmlLang {
315 if(Attributes != null)
316 for (int i = 0; i < Attributes.Count; i++) {
317 XmlAttribute attr = Attributes [i];
318 if(attr.Name == "xml:lang")
321 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
325 internal virtual XmlSpace XmlSpace {
327 if(Attributes != null) {
328 for (int i = 0; i < Attributes.Count; i++) {
329 XmlAttribute attr = Attributes [i];
330 if(attr.Name == "xml:space") {
332 case "preserve": return XmlSpace.Preserve;
333 case "default": return XmlSpace.Default;
339 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
344 public virtual IXmlSchemaInfo SchemaInfo {
354 public virtual XmlNode AppendChild (XmlNode newChild)
356 // AppendChild(n) is equivalent to InsertBefore(n, null)
357 return InsertBefore (newChild, null);
360 internal XmlNode AppendChild (XmlNode newChild, bool checkNodeType)
362 return InsertBefore (newChild, null, checkNodeType, true);
365 public virtual XmlNode Clone ()
367 // By MS document, it is equivalent to CloneNode(true).
368 return this.CloneNode (true);
371 public abstract XmlNode CloneNode (bool deep);
374 public virtual XPathNavigator CreateNavigator ()
376 // XmlDocument has overriden definition, so it is safe
377 // to use OwnerDocument here.
378 return OwnerDocument.CreateNavigator (this);
381 public XPathNavigator CreateNavigator ()
383 XmlDocument document = this.NodeType == XmlNodeType.Document ?
384 this as XmlDocument : this.ownerDocument;
385 return document.CreateNavigator (this);
389 public IEnumerator GetEnumerator ()
391 return ChildNodes.GetEnumerator ();
394 public virtual string GetNamespaceOfPrefix (string prefix)
398 throw new ArgumentNullException ("prefix");
401 return XmlNamespaceManager.XmlnsXml;
403 return XmlNamespaceManager.XmlnsXmlns;
409 case XmlNodeType.Attribute:
410 node = ((XmlAttribute) this).OwnerElement;
414 case XmlNodeType.Element:
422 while (node != null) {
423 if (node.Prefix == prefix)
424 return node.NamespaceURI;
425 if (node.NodeType == XmlNodeType.Element &&
426 ((XmlElement) node).HasAttributes) {
427 int count = node.Attributes.Count;
428 for (int i = 0; i < count; i++) {
429 XmlAttribute attr = node.Attributes [i];
430 if (prefix == attr.LocalName && attr.Prefix == "xmlns"
431 || attr.Name == "xmlns" && prefix == String.Empty)
435 node = node.ParentNode;
440 public virtual string GetPrefixOfNamespace (string namespaceURI)
443 switch (namespaceURI) {
444 case XmlNamespaceManager.XmlnsXml:
445 return XmlNamespaceManager.PrefixXml;
446 case XmlNamespaceManager.XmlnsXmlns:
447 return XmlNamespaceManager.PrefixXmlns;
453 case XmlNodeType.Attribute:
454 node = ((XmlAttribute) this).OwnerElement;
456 case XmlNodeType.Element:
464 while (node != null) {
465 if (node.NodeType == XmlNodeType.Element &&
466 ((XmlElement) node).HasAttributes) {
467 for (int i = 0; i < node.Attributes.Count; i++) {
468 XmlAttribute attr = node.Attributes [i];
469 if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
470 return attr.LocalName;
471 else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
475 node = node.ParentNode;
480 object ICloneable.Clone ()
485 IEnumerator IEnumerable.GetEnumerator ()
487 return GetEnumerator ();
490 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
492 // InsertAfter(n1, n2) is equivalent to InsertBefore(n1, n2.PreviousSibling).
494 // I took this way because current implementation
495 // Calling InsertBefore() in this method is faster than
496 // the counterpart, since NextSibling is faster than
497 // PreviousSibling (these children are forward-only list).
498 XmlNode argNode = null;
499 if (refChild != null)
500 argNode = refChild.NextSibling;
501 else if (FirstChild != null)
502 argNode = FirstChild;
503 return InsertBefore (newChild, argNode);
506 public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
508 return InsertBefore (newChild, refChild, true, true);
511 // check for the node to be one of node ancestors
512 internal bool IsAncestor (XmlNode newChild)
514 XmlNode currNode = this.ParentNode;
515 while(currNode != null)
517 if(currNode == newChild)
519 currNode = currNode.ParentNode;
524 internal XmlNode InsertBefore (XmlNode newChild, XmlNode refChild, bool checkNodeType, bool raiseEvent)
527 CheckNodeInsertion (newChild, refChild);
529 if (newChild == refChild)
532 IHasXmlChildNode l = (IHasXmlChildNode) this;
534 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
537 ownerDoc.onNodeInserting (newChild, this);
539 if (newChild.ParentNode != null)
540 newChild.ParentNode.RemoveChild (newChild, checkNodeType);
542 if (newChild.NodeType == XmlNodeType.DocumentFragment) {
543 // This recursively invokes events. (It is compatible with MS implementation.)
544 while (newChild.FirstChild != null)
545 this.InsertBefore (newChild.FirstChild, refChild);
548 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
549 newLinkedChild.parentNode = this;
551 if (refChild == null) {
552 // newChild is the last child:
553 // * set newChild as NextSibling of the existing lastchild
554 // * set LastChild = newChild
555 // * set NextSibling of newChild as FirstChild
556 if (l.LastLinkedChild != null) {
557 XmlLinkedNode formerFirst = (XmlLinkedNode) FirstChild;
558 l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
559 l.LastLinkedChild = newLinkedChild;
560 newLinkedChild.NextLinkedSibling = formerFirst;
562 l.LastLinkedChild = newLinkedChild;
563 l.LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
566 // newChild is not the last child:
567 // * if newchild is first, then set next of lastchild is newChild.
568 // otherwise, set next of previous sibling to newChild
569 // * set next of newChild to refChild
570 XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
572 l.LastLinkedChild.NextLinkedSibling = newLinkedChild;
574 prev.NextLinkedSibling = newLinkedChild;
575 newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
577 switch (newChild.NodeType) {
578 case XmlNodeType.EntityReference:
579 ((XmlEntityReference) newChild).SetReferencedEntityContent ();
581 case XmlNodeType.Entity:
583 case XmlNodeType.DocumentType:
588 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
593 private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
595 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
597 if (NodeType != XmlNodeType.Element &&
598 NodeType != XmlNodeType.Attribute &&
599 NodeType != XmlNodeType.Document &&
600 NodeType != XmlNodeType.DocumentFragment)
601 throw new InvalidOperationException (String.Format ("Node cannot be appended to current node {0}.", NodeType));
604 case XmlNodeType.Attribute:
605 switch (newChild.NodeType) {
606 case XmlNodeType.Text:
607 case XmlNodeType.EntityReference:
610 throw new InvalidOperationException (String.Format (
611 "Cannot insert specified type of node {0} as a child of this node {1}.",
612 newChild.NodeType, NodeType));
615 case XmlNodeType.Element:
616 switch (newChild.NodeType) {
617 case XmlNodeType.Attribute:
618 case XmlNodeType.Document:
619 case XmlNodeType.DocumentType:
620 case XmlNodeType.Entity:
621 case XmlNodeType.Notation:
622 case XmlNodeType.XmlDeclaration:
623 throw new InvalidOperationException ("Cannot insert specified type of node as a child of this node.");
629 throw new InvalidOperationException ("The node is readonly.");
631 if (newChild.OwnerDocument != ownerDoc)
632 throw new ArgumentException ("Can't append a node created by another document.");
634 if (refChild != null) {
635 if (refChild.ParentNode != this)
636 throw new ArgumentException ("The reference node is not a child of this node.");
639 if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement) && newChild != ownerDoc.DocumentElement)
640 throw new XmlException ("multiple document element not allowed.");
642 // checking validity finished. then appending...
645 if (newChild == this || IsAncestor (newChild))
646 throw new ArgumentException("Cannot insert a node or any ancestor of that node as a child of itself.");
650 public virtual void Normalize ()
652 StringBuilder tmpBuilder = new StringBuilder ();
653 int count = this.ChildNodes.Count;
655 for (int i = 0; i < count; i++) {
656 XmlNode c = ChildNodes [i];
657 switch (c.NodeType) {
658 case XmlNodeType.Text:
659 case XmlNodeType.Whitespace:
660 case XmlNodeType.SignificantWhitespace:
661 tmpBuilder.Append (c.Value);
665 NormalizeRange (start, i, tmpBuilder);
666 // Continue to normalize from next node.
672 NormalizeRange (start, count, tmpBuilder);
676 private void NormalizeRange (int start, int i, StringBuilder tmpBuilder)
679 // If Texts and Whitespaces are mixed, Text takes precedence to remain.
680 // i.e. Whitespace should be removed.
681 for (int j = start; j < i; j++) {
682 XmlNode keep = ChildNodes [j];
683 if (keep.NodeType == XmlNodeType.Text) {
687 else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
689 // but don't break up to find Text nodes.
693 for (int del = start; del < keepPos; del++)
694 RemoveChild (ChildNodes [start]);
695 int rest = i - keepPos - 1;
696 for (int del = 0; del < rest; del++) {
697 RemoveChild (ChildNodes [start + 1]);
702 ChildNodes [start].Value = tmpBuilder.ToString ();
703 // otherwise nothing to be normalized
705 tmpBuilder.Length = 0;
708 public virtual XmlNode PrependChild (XmlNode newChild)
710 return InsertAfter (newChild, null);
713 public virtual void RemoveAll ()
715 if (Attributes != null)
716 Attributes.RemoveAll ();
718 for (XmlNode node = FirstChild; node != null; node = next) {
719 next = node.NextSibling;
724 public virtual XmlNode RemoveChild (XmlNode oldChild)
726 return RemoveChild (oldChild, true);
729 private void CheckNodeRemoval ()
731 if (NodeType != XmlNodeType.Attribute &&
732 NodeType != XmlNodeType.Element &&
733 NodeType != XmlNodeType.Document &&
734 NodeType != XmlNodeType.DocumentFragment)
735 throw new ArgumentException (String.Format ("This {0} node cannot remove its child.", NodeType));
738 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
741 internal XmlNode RemoveChild (XmlNode oldChild, bool checkNodeType)
743 if (oldChild == null)
744 throw new NullReferenceException ();
745 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
746 if(oldChild.ParentNode != this)
747 throw new ArgumentException ("The node to be removed is not a child of this node.");
750 ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
755 IHasXmlChildNode l = (IHasXmlChildNode) this;
757 if (Object.ReferenceEquals (l.LastLinkedChild, l.LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (l.LastLinkedChild, oldChild))
758 // If there is only one children, simply clear.
759 l.LastLinkedChild = null;
761 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
762 XmlLinkedNode beforeLinkedChild = l.LastLinkedChild;
763 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
765 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, l.LastLinkedChild) == false &&
766 Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
767 beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
769 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
770 throw new ArgumentException ();
772 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
774 // Each derived class may have its own l.LastLinkedChild, so we must set it explicitly.
775 if (oldLinkedChild.NextLinkedSibling == firstChild)
776 l.LastLinkedChild = beforeLinkedChild;
778 oldLinkedChild.NextLinkedSibling = null;
782 ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
783 oldChild.parentNode = null; // clear parent 'after' above logic.
788 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
790 if(oldChild.ParentNode != this)
791 throw new ArgumentException ("The node to be removed is not a child of this node.");
793 if (newChild == this || IsAncestor (newChild))
794 throw new InvalidOperationException("Cannot insert a node or any ancestor of that node as a child of itself.");
796 XmlNode next = oldChild.NextSibling;
797 RemoveChild (oldChild);
798 InsertBefore (newChild, next);
802 // WARNING: don't use this member outside XmlAttribute nodes.
803 internal XmlElement AttributeOwnerElement {
804 get { return (XmlElement) parentNode; }
805 set { parentNode = value; }
808 internal void SearchDescendantElements (string name, bool matchAll, ArrayList list)
810 for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
811 if (n.NodeType != XmlNodeType.Element)
813 if (matchAll || n.Name == name)
815 n.SearchDescendantElements (name, matchAll, list);
819 internal void SearchDescendantElements (string name, bool matchAllName, string ns, bool matchAllNS, ArrayList list)
821 for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
822 if (n.NodeType != XmlNodeType.Element)
824 if ((matchAllName || n.LocalName == name)
825 && (matchAllNS || n.NamespaceURI == ns))
827 n.SearchDescendantElements (name, matchAllName, ns, matchAllNS, list);
831 public XmlNodeList SelectNodes (string xpath)
833 return SelectNodes (xpath, null);
836 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
838 XPathNavigator nav = CreateNavigator ();
839 XPathExpression expr = nav.Compile (xpath);
841 expr.SetContext (nsmgr);
842 XPathNodeIterator iter = nav.Select (expr);
844 ArrayList rgNodes = new ArrayList ();
845 while (iter.MoveNext ())
847 rgNodes.Add (((IHasXmlNode) iter.Current).GetNode ());
849 return new XmlNodeArrayList (rgNodes);
851 return new XmlIteratorNodeList (iter);
854 public XmlNode SelectSingleNode (string xpath)
856 return SelectSingleNode (xpath, null);
859 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
861 XPathNavigator nav = CreateNavigator ();
862 XPathExpression expr = nav.Compile (xpath);
864 expr.SetContext (nsmgr);
865 XPathNodeIterator iter = nav.Select (expr);
866 if (!iter.MoveNext ())
868 return ((IHasXmlNode) iter.Current).GetNode ();
871 public virtual bool Supports (string feature, string version)
873 if (String.Compare (feature, "xml", true, CultureInfo.InvariantCulture) == 0 // not case-sensitive
874 && (String.Compare (version, "1.0", true, CultureInfo.InvariantCulture) == 0
875 || String.Compare (version, "2.0", true, CultureInfo.InvariantCulture) == 0))
881 public abstract void WriteContentTo (XmlWriter w);
883 public abstract void WriteTo (XmlWriter w);
885 // It parses this and all the ancestor elements,
886 // find 'xmlns' declarations, stores and then return them.
887 internal XmlNamespaceManager ConstructNamespaceManager ()
889 XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
890 XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
891 XmlElement el = null;
892 switch(this.NodeType) {
893 case XmlNodeType.Attribute:
894 el = ((XmlAttribute)this).OwnerElement;
896 case XmlNodeType.Element:
897 el = this as XmlElement;
900 el = this.ParentNode as XmlElement;
905 for (int i = 0; i < el.Attributes.Count; i++) {
906 XmlAttribute attr = el.Attributes [i];
907 if(attr.Prefix == "xmlns") {
908 if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
909 nsmgr.AddNamespace (attr.LocalName, attr.Value);
910 } else if(attr.Name == "xmlns") {
911 if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
912 nsmgr.AddNamespace (String.Empty, attr.Value);
915 // When reached to document, then it will set null value :)
916 el = el.ParentNode as XmlElement;