5 // Kral Ferch <kral_ferch@hotmail.com>
6 // Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
9 // (C) 2002 Atsushi Enomoto
13 using System.Collections;
16 using System.Xml.XPath;
20 public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
24 XmlDocument ownerDocument;
31 internal XmlNode (XmlDocument ownerDocument)
33 this.ownerDocument = ownerDocument;
40 public virtual XmlAttributeCollection Attributes {
44 public virtual string BaseURI {
46 // Isn't it conformant to W3C XML Base Recommendation?
47 // As far as I tested, there are not...
48 return (ParentNode != null) ? ParentNode.BaseURI : OwnerDocument.BaseURI;
52 public virtual XmlNodeList ChildNodes {
54 return new XmlNodeListChildren (this);
58 public virtual XmlNode FirstChild {
60 if (LastChild != null) {
61 return LastLinkedChild.NextLinkedSibling;
69 public virtual bool HasChildNodes {
70 get { return LastChild != null; }
73 [MonoTODO("confirm whether this way is right for each not-overriden types.")]
74 public virtual string InnerText {
76 StringBuilder builder = new StringBuilder ();
77 AppendChildValues (this, builder);
78 return builder.ToString ();
81 set { throw new NotImplementedException (); }
84 private void AppendChildValues (XmlNode parent, StringBuilder builder)
86 XmlNode node = parent.FirstChild;
\r
88 while (node != null) {
\r
89 switch (node.NodeType) {
90 case XmlNodeType.Text:
91 case XmlNodeType.CDATA:
92 case XmlNodeType.SignificantWhitespace:
93 case XmlNodeType.Whitespace:
94 builder.Append (node.Value);
\r
97 AppendChildValues (node, builder);
\r
98 node = node.NextSibling;
\r
102 public virtual string InnerXml {
104 StringWriter sw = new StringWriter ();
105 XmlTextWriter xtw = new XmlTextWriter (sw);
107 WriteContentTo (xtw);
109 return sw.GetStringBuilder ().ToString ();
113 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
117 public virtual bool IsReadOnly {
118 get { return false; }
121 [System.Runtime.CompilerServices.IndexerName("Item")]
122 public virtual XmlElement this [string name] {
124 foreach (XmlNode node in ChildNodes) {
125 if ((node.NodeType == XmlNodeType.Element) &&
126 (node.Name == name)) {
127 return (XmlElement) node;
135 [System.Runtime.CompilerServices.IndexerName("Item")]
136 public virtual XmlElement this [string localname, string ns] {
138 foreach (XmlNode node in ChildNodes) {
139 if ((node.NodeType == XmlNodeType.Element) &&
140 (node.LocalName == localname) &&
141 (node.NamespaceURI == ns)) {
142 return (XmlElement) node;
150 public virtual XmlNode LastChild {
151 get { return LastLinkedChild; }
154 internal virtual XmlLinkedNode LastLinkedChild {
159 public abstract string LocalName { get; }
161 public abstract string Name { get; }
163 public virtual string NamespaceURI {
164 get { return String.Empty; }
167 public virtual XmlNode NextSibling {
171 public abstract XmlNodeType NodeType { get; }
173 internal virtual XPathNodeType XPathNodeType {
175 throw new InvalidOperationException ();
179 public virtual string OuterXml {
181 StringWriter sw = new StringWriter ();
182 XmlTextWriter xtw = new XmlTextWriter (sw);
186 return sw.ToString ();
190 public virtual XmlDocument OwnerDocument {
191 get { return ownerDocument; }
194 public virtual XmlNode ParentNode {
195 get { return parentNode; }
198 public virtual string Prefix {
199 get { return String.Empty; }
203 public virtual XmlNode PreviousSibling {
207 public virtual string Value {
209 set { throw new InvalidOperationException ("This node does not have a value"); }
212 internal virtual string XmlLang {
214 if(Attributes != null)
215 foreach(XmlAttribute attr in Attributes)
216 if(attr.Name == "xml:lang")
218 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
222 internal virtual XmlSpace XmlSpace {
224 if(Attributes != null) {
225 foreach(XmlAttribute attr in Attributes) {
226 if(attr.Name == "xml:space") {
228 case "preserve": return XmlSpace.Preserve;
229 case "default": return XmlSpace.Default;
235 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
243 public virtual XmlNode AppendChild (XmlNode newChild)
245 // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
246 return InsertBefore (newChild, null);
249 public virtual XmlNode Clone ()
251 // By MS document, it is equivalent to CloneNode(true).
252 return this.CloneNode (true);
255 public abstract XmlNode CloneNode (bool deep);
258 public XPathNavigator CreateNavigator ()
260 XmlDocument document = this.NodeType == XmlNodeType.Document ?
261 this as XmlDocument : this.ownerDocument;
262 return document.CreateNavigator (this);
265 public IEnumerator GetEnumerator ()
267 return new XmlNodeListChildren (this).GetEnumerator ();
270 public virtual string GetNamespaceOfPrefix (string prefix)
274 case XmlNodeType.Attribute:
275 node = ((XmlAttribute) this).OwnerElement;
277 case XmlNodeType.Element:
285 while (node.NodeType != XmlNodeType.Document) {
286 foreach (XmlAttribute attr in node.Attributes) {
287 if (prefix == attr.LocalName && attr.Prefix == "xmlns"
288 || attr.Name == "xmlns" && prefix == String.Empty)
291 node = node.ParentNode;
296 public virtual string GetPrefixOfNamespace (string namespaceURI)
300 case XmlNodeType.Attribute:
301 node = ((XmlAttribute) this).OwnerElement;
303 case XmlNodeType.Element:
311 while (node.NodeType != XmlNodeType.Document) {
312 foreach (XmlAttribute attr in node.Attributes) {
313 if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
314 return attr.LocalName;
315 else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
318 node = node.ParentNode;
323 object ICloneable.Clone ()
328 IEnumerator IEnumerable.GetEnumerator ()
330 return GetEnumerator ();
333 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
335 // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
337 // I took this way because current implementation
338 // Calling InsertAfter() from InsertBefore() is
339 // subsequently to use 'NextSibling' which is
340 // faster than 'PreviousSibling' (these children are
341 // forward-only linked list).
342 XmlNode argNode = null;
344 argNode = refChild.NextSibling;
345 else if(ChildNodes.Count > 0)
346 argNode = FirstChild;
347 return InsertBefore (newChild, argNode);
350 [MonoTODO("If inserted node is entity reference, then check conforming entity. Wait for DTD implementation.")]
351 public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
353 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
355 if (NodeType != XmlNodeType.Element &&
356 NodeType != XmlNodeType.Attribute &&
357 NodeType != XmlNodeType.Document &&
358 NodeType != XmlNodeType.DocumentFragment)
359 throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
362 case XmlNodeType.Attribute:
363 switch (newChild.NodeType) {
364 case XmlNodeType.Text:
365 case XmlNodeType.EntityReference:
368 throw new ArgumentException (String.Format (
369 "Cannot insert specified type of node {0} as a child of this node {0}.",
370 newChild.NodeType, NodeType));
373 case XmlNodeType.Element:
374 switch (newChild.NodeType) {
375 case XmlNodeType.Attribute:
376 case XmlNodeType.Document:
377 case XmlNodeType.DocumentType:
378 case XmlNodeType.Entity:
379 case XmlNodeType.Notation:
380 case XmlNodeType.XmlDeclaration:
381 throw new ArgumentException ("Cannot insert specified type of node as a child of this node.");
387 throw new ArgumentException ("The specified node is readonly.");
389 if (newChild.OwnerDocument != ownerDoc)
390 throw new ArgumentException ("Can't append a node created by another document.");
392 if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
393 throw new ArgumentException ("argument nodes are on the different documents.");
395 // This check is done by MS.NET 1.0, but isn't done for MS.NET 1.1.
396 // Skip this check in the meantime...
397 // if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement))
398 // throw new XmlException ("multiple document element not allowed.");
400 // checking validity finished. then appending...
402 return insertBeforeIntern (newChild, refChild);
405 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
407 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
409 ownerDoc.onNodeInserting (newChild, this);
411 if(newChild.ParentNode != null)
412 newChild.ParentNode.RemoveChild (newChild);
414 if(newChild.NodeType == XmlNodeType.DocumentFragment) {
415 int x = newChild.ChildNodes.Count;
416 for(int i=0; i<x; i++) {
417 XmlNode n = newChild.ChildNodes [0];
418 this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
422 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
423 XmlLinkedNode lastLinkedChild = LastLinkedChild;
425 newLinkedChild.parentNode = this;
427 if(refChild == null) {
429 // * set nextSibling of previous lastchild to newChild
430 // * set lastchild = newChild
431 // * set next of newChild to firstChild
432 if(LastLinkedChild != null) {
433 XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
434 LastLinkedChild.NextLinkedSibling = newLinkedChild;
435 LastLinkedChild = newLinkedChild;
436 newLinkedChild.NextLinkedSibling = formerFirst;
439 LastLinkedChild = newLinkedChild;
440 LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
444 // append not last, so:
445 // * if newchild is first, then set next of lastchild is newChild.
446 // otherwise, set next of previous sibling to newChild
447 // * set next of newChild to refChild
448 XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
450 LastLinkedChild.NextLinkedSibling = newLinkedChild;
452 prev.NextLinkedSibling = newLinkedChild;
453 newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
455 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
461 public virtual void Normalize ()
463 throw new NotImplementedException ();
466 public virtual XmlNode PrependChild (XmlNode newChild)
468 return InsertAfter (newChild, null);
471 public virtual void RemoveAll ()
473 if (Attributes != null)
474 Attributes.RemoveAll ();
476 for (XmlNode node = FirstChild; node != null; node = next) {
477 next = node.NextSibling;
482 public virtual XmlNode RemoveChild (XmlNode oldChild)
484 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
485 if(oldChild.ParentNode != this)
486 throw new XmlException ("specified child is not child of this node.");
488 ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
490 if (NodeType != XmlNodeType.Attribute &&
491 NodeType != XmlNodeType.Element &&
492 NodeType != XmlNodeType.Document &&
493 NodeType != XmlNodeType.DocumentFragment)
494 throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
497 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
499 if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
500 // If there is only one children, simply clear.
501 LastLinkedChild = null;
503 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
504 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
505 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
507 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
508 Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
509 beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
511 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
512 throw new ArgumentException ();
514 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
516 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
517 if (oldLinkedChild.NextLinkedSibling == firstChild)
518 this.LastLinkedChild = beforeLinkedChild;
520 oldLinkedChild.NextLinkedSibling = null;
523 ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
524 oldChild.parentNode = null; // clear parent 'after' above logic.
529 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
531 if(oldChild.ParentNode != this)
532 throw new InvalidOperationException ("oldChild is not a child of this node.");
533 XmlNode parent = this.ParentNode;
534 while(parent != null) {
535 if(newChild == parent)
536 throw new InvalidOperationException ("newChild is ancestor of this node.");
537 parent = parent.ParentNode;
539 foreach(XmlNode n in ChildNodes) {
541 XmlNode prev = oldChild.PreviousSibling;
542 RemoveChild (oldChild);
543 InsertAfter (newChild, prev);
550 public XmlNodeList SelectNodes (string xpath)
552 return SelectNodes (xpath, null);
556 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
558 XPathNavigator nav = CreateNavigator ();
559 XPathExpression expr = nav.Compile (xpath);
561 expr.SetContext (nsmgr);
562 XPathNodeIterator iter = nav.Select (expr);
563 ArrayList rgNodes = new ArrayList ();
564 while (iter.MoveNext ())
566 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
568 return new XmlNodeArrayList (rgNodes);
571 public XmlNode SelectSingleNode (string xpath)
573 return SelectSingleNode (xpath, null);
577 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
579 XPathNavigator nav = CreateNavigator ();
580 XPathExpression expr = nav.Compile (xpath);
582 expr.SetContext (nsmgr);
583 XPathNodeIterator iter = nav.Select (expr);
584 if (!iter.MoveNext ())
586 return ((XmlDocumentNavigator) iter.Current).Node;
589 // internal void SetParentNode (XmlNode parent)
591 // parentNode = parent;
595 public virtual bool Supports (string feature, string version)
597 throw new NotImplementedException ();
600 public abstract void WriteContentTo (XmlWriter w);
602 public abstract void WriteTo (XmlWriter w);
604 // It parses this and all the ancestor elements,
605 // find 'xmlns' declarations, stores and then return them.
607 internal XmlNamespaceManager ConstructNamespaceManager ()
609 XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
610 XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
611 XmlElement el = null;
612 switch(this.NodeType) {
613 case XmlNodeType.Attribute:
614 el = ((XmlAttribute)this).OwnerElement;
616 case XmlNodeType.Element:
617 el = this as XmlElement;
620 el = this.ParentNode as XmlElement;
625 foreach(XmlAttribute attr in el.Attributes) {
626 if(attr.Prefix == "xmlns") {
627 if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
628 nsmgr.AddNamespace (attr.LocalName, attr.Value);
629 } else if(attr.Name == "xmlns") {
630 if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
631 nsmgr.AddNamespace (String.Empty, attr.Value);
634 // When reached to document, then it will set null value :)
635 el = el.ParentNode as XmlElement;