2003-07-29 Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
[mono.git] / mcs / class / System.XML / System.Xml / XmlNode.cs
1 //
2 // System.Xml.XmlNode
3 //
4 // Author:
5 //   Kral Ferch <kral_ferch@hotmail.com>
6 //   Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
7 //
8 // (C) 2002 Kral Ferch
9 // (C) 2002 Atsushi Enomoto
10 //
11
12 using System;
13 using System.Collections;
14 using System.IO;
15 using System.Text;
16 using System.Xml.XPath;
17
18 namespace System.Xml
19 {
20         public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
21         {
22                 #region Fields
23
24                 XmlDocument ownerDocument;
25                 XmlNode parentNode;
26
27                 #endregion
28
29                 #region Constructors
30
31                 internal XmlNode (XmlDocument ownerDocument)
32                 {
33                         this.ownerDocument = ownerDocument;
34                 }
35
36                 #endregion
37
38                 #region Properties
39
40                 public virtual XmlAttributeCollection Attributes {
41                         get { return null; }
42                 }
43
44                 public virtual string BaseURI {
45                         get {
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;
49                         }
50                 }
51
52                 public virtual XmlNodeList ChildNodes {
53                         get {
54                                 return new XmlNodeListChildren (this);
55                         }
56                 }
57
58                 public virtual XmlNode FirstChild {
59                         get {
60                                 if (LastChild != null) {
61                                         return LastLinkedChild.NextLinkedSibling;
62                                 }
63                                 else {
64                                         return null;
65                                 }
66                         }
67                 }
68
69                 public virtual bool HasChildNodes {
70                         get { return LastChild != null; }
71                 }
72
73                 [MonoTODO("confirm whether this way is right for each not-overriden types.")]
74                 public virtual string InnerText {
75                         get {
76                                 StringBuilder builder = new StringBuilder ();
77                                 AppendChildValues (this, builder);
78                                 return builder.ToString ();
79                         }
80
81                         set { throw new NotImplementedException (); }
82                 }
83
84                 private void AppendChildValues (XmlNode parent, StringBuilder builder)
85                 {
86                         XmlNode node = parent.FirstChild;\r
87 \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
95                                         break;\r
96                                 }\r
97                                 AppendChildValues (node, builder);\r
98                                 node = node.NextSibling;\r
99                         }\r
100                 }
101
102                 public virtual string InnerXml {
103                         get {
104                                 StringWriter sw = new StringWriter ();
105                                 XmlTextWriter xtw = new XmlTextWriter (sw);
106
107                                 WriteContentTo (xtw);
108
109                                 return sw.GetStringBuilder ().ToString ();
110                         }
111
112                         set {
113                                 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
114                         }
115                 }
116
117                 public virtual bool IsReadOnly {
118                         get { return false; }
119                 }
120
121                 [System.Runtime.CompilerServices.IndexerName("Item")]
122                 public virtual XmlElement this [string name] {
123                         get { 
124                                 foreach (XmlNode node in ChildNodes) {
125                                         if ((node.NodeType == XmlNodeType.Element) &&
126                                             (node.Name == name)) {
127                                                 return (XmlElement) node;
128                                         }
129                                 }
130
131                                 return null;
132                         }
133                 }
134
135                 [System.Runtime.CompilerServices.IndexerName("Item")]
136                 public virtual XmlElement this [string localname, string ns] {
137                         get { 
138                                 foreach (XmlNode node in ChildNodes) {
139                                         if ((node.NodeType == XmlNodeType.Element) &&
140                                             (node.LocalName == localname) && 
141                                             (node.NamespaceURI == ns)) {
142                                                 return (XmlElement) node;
143                                         }
144                                 }
145
146                                 return null;
147                         }
148                 }
149
150                 public virtual XmlNode LastChild {
151                         get { return LastLinkedChild; }
152                 }
153
154                 internal virtual XmlLinkedNode LastLinkedChild {
155                         get { return null; }
156                         set { }
157                 }
158
159                 public abstract string LocalName { get; }
160
161                 public abstract string Name     { get; }
162
163                 public virtual string NamespaceURI {
164                         get { return String.Empty; }
165                 }
166
167                 public virtual XmlNode NextSibling {
168                         get { return null; }
169                 }
170
171                 public abstract XmlNodeType NodeType { get;     }
172
173                 internal virtual XPathNodeType XPathNodeType {
174                         get {
175                                 throw new InvalidOperationException ();
176                         }
177                 }
178
179                 public virtual string OuterXml {
180                         get {
181                                 StringWriter sw = new StringWriter ();
182                                 XmlTextWriter xtw = new XmlTextWriter (sw);
183
184                                 WriteTo (xtw);
185
186                                 return sw.ToString ();
187                         }
188                 }
189
190                 public virtual XmlDocument OwnerDocument {
191                         get { return ownerDocument; }
192                 }
193
194                 public virtual XmlNode ParentNode {
195                         get { return parentNode; }
196                 }
197
198                 public virtual string Prefix {
199                         get { return String.Empty; }
200                         set {}
201                 }
202
203                 public virtual XmlNode PreviousSibling {
204                         get { return null; }
205                 }
206
207                 public virtual string Value {
208                         get { return null; }
209                         set { throw new InvalidOperationException ("This node does not have a value"); }
210                 }
211
212                 internal virtual string XmlLang {
213                         get {
214                                 if(Attributes != null)
215                                         foreach(XmlAttribute attr in Attributes)
216                                                 if(attr.Name == "xml:lang")
217                                                         return attr.Value;
218                                 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
219                         }
220                 }
221
222                 internal virtual XmlSpace XmlSpace {
223                         get {
224                                 if(Attributes != null) {
225                                         foreach(XmlAttribute attr in Attributes) {
226                                                 if(attr.Name == "xml:space") {
227                                                         switch(attr.Value) {
228                                                         case "preserve": return XmlSpace.Preserve;
229                                                         case "default": return XmlSpace.Default;
230                                                         }
231                                                         break;
232                                                 }
233                                         }
234                                 }
235                                 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
236                         }
237                 }
238
239                 #endregion
240
241                 #region Methods
242
243                 public virtual XmlNode AppendChild (XmlNode newChild)
244                 {
245                         // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
246                         return InsertBefore (newChild, null);
247                 }
248
249                 public virtual XmlNode Clone ()
250                 {
251                         // By MS document, it is equivalent to CloneNode(true).
252                         return this.CloneNode (true);
253                 }
254
255                 public abstract XmlNode CloneNode (bool deep);
256
257                 [MonoTODO]
258                 public XPathNavigator CreateNavigator ()
259                 {
260                         XmlDocument document = this.NodeType == XmlNodeType.Document ?
261                                 this as XmlDocument : this.ownerDocument;
262                         return document.CreateNavigator (this);
263                 }
264
265                 public IEnumerator GetEnumerator ()
266                 {
267                         return new XmlNodeListChildren (this).GetEnumerator ();
268                 }
269
270                 public virtual string GetNamespaceOfPrefix (string prefix)
271                 {
272                         XmlNode node;
273                         switch (NodeType) {
274                         case XmlNodeType.Attribute:
275                                 node = ((XmlAttribute) this).OwnerElement;
276                                 break;
277                         case XmlNodeType.Element:
278                                 node = this;
279                                 break;
280                         default:
281                                 node = ParentNode;
282                                 break;
283                         }
284
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)
289                                                 return attr.Value;
290                                 }
291                                 node = node.ParentNode;
292                         }
293                         return null;
294                 }
295
296                 public virtual string GetPrefixOfNamespace (string namespaceURI)
297                 {
298                         XmlNode node;
299                         switch (NodeType) {
300                         case XmlNodeType.Attribute:
301                                 node = ((XmlAttribute) this).OwnerElement;
302                                 break;
303                         case XmlNodeType.Element:
304                                 node = this;
305                                 break;
306                         default:
307                                 node = ParentNode;
308                                 break;
309                         }
310
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)
316                                                 return String.Empty;
317                                 }
318                                 node = node.ParentNode;
319                         }
320                         return String.Empty;
321                 }
322
323                 object ICloneable.Clone ()
324                 {
325                         return Clone ();
326                 }
327
328                 IEnumerator IEnumerable.GetEnumerator ()
329                 {
330                         return GetEnumerator ();
331                 }
332
333                 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
334                 {
335                         // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
336
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;
343                         if(refChild != null)
344                                 argNode = refChild.NextSibling;
345                         else if(ChildNodes.Count > 0)
346                                 argNode = FirstChild;
347                         return InsertBefore (newChild, argNode);
348                 }
349
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)
352                 {
353                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
354
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));
360
361                         switch (NodeType) {
362                         case XmlNodeType.Attribute:
363                                 switch (newChild.NodeType) {
364                                 case XmlNodeType.Text:
365                                 case XmlNodeType.EntityReference:
366                                         break;
367                                 default:
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));
371                                 }
372                                 break;
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.");
382                                 }
383                                 break;
384                         }
385
386                         if (IsReadOnly)
387                                 throw new ArgumentException ("The specified node is readonly.");
388
389                         if (newChild.OwnerDocument != ownerDoc)
390                                 throw new ArgumentException ("Can't append a node created by another document.");
391
392                         if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
393                                         throw new ArgumentException ("argument nodes are on the different documents.");
394
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.");
399
400                         // checking validity finished. then appending...
401
402                         return insertBeforeIntern (newChild, refChild);
403                 }
404
405                 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
406                 {
407                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
408
409                         ownerDoc.onNodeInserting (newChild, this);
410
411                         if(newChild.ParentNode != null)
412                                 newChild.ParentNode.RemoveChild (newChild);
413
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.)
419                                 }
420                         }
421                         else {
422                                 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
423                                 XmlLinkedNode lastLinkedChild = LastLinkedChild;
424
425                                 newLinkedChild.parentNode = this;
426
427                                 if(refChild == null) {
428                                         // append last, so:
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;
437                                         }
438                                         else {
439                                                 LastLinkedChild = newLinkedChild;
440                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;     // FirstChild
441                                         }
442                                 }
443                                 else {
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;
449                                         if(prev == null)
450                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;
451                                         else
452                                                 prev.NextLinkedSibling = newLinkedChild;
453                                         newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
454                                 }
455                                 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
456                         }
457                         return newChild;
458                 }
459
460                 [MonoTODO]
461                 public virtual void Normalize ()
462                 {
463                         throw new NotImplementedException ();
464                 }
465
466                 public virtual XmlNode PrependChild (XmlNode newChild)
467                 {
468                         return InsertAfter (newChild, null);
469                 }
470
471                 public virtual void RemoveAll ()
472                 {
473                         if (Attributes != null)
474                                 Attributes.RemoveAll ();
475                         XmlNode next = null;
476                         for (XmlNode node = FirstChild; node != null; node = next) {
477                                 next = node.NextSibling;
478                                 RemoveChild (node);
479                         }
480                 }
481
482                 public virtual XmlNode RemoveChild (XmlNode oldChild)
483                 {
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.");
487
488                         ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
489
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));
495
496                         if (IsReadOnly)
497                                 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
498
499                         if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
500                                 // If there is only one children, simply clear.
501                                 LastLinkedChild = null;
502                         else {
503                                 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
504                                 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
505                                 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
506                                 
507                                 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false && 
508                                         Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
509                                         beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
510
511                                 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
512                                         throw new ArgumentException ();
513
514                                 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
515
516                                 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
517                                 if (oldLinkedChild.NextLinkedSibling == firstChild)
518                                         this.LastLinkedChild = beforeLinkedChild;
519
520                                 oldLinkedChild.NextLinkedSibling = null;
521                                 }
522
523                         ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
524                         oldChild.parentNode = null;     // clear parent 'after' above logic.
525
526                         return oldChild;
527                 }
528
529                 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
530                 {
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;
538                         }
539                         foreach(XmlNode n in ChildNodes) {
540                                 if(n == oldChild) {
541                                         XmlNode prev = oldChild.PreviousSibling;
542                                         RemoveChild (oldChild);
543                                         InsertAfter (newChild, prev);
544                                         break;
545                                 }
546                         }
547                         return oldChild;
548                 }
549
550                 public XmlNodeList SelectNodes (string xpath)
551                 {
552                         return SelectNodes (xpath, null);
553                 }
554
555                 [MonoTODO]
556                 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
557                 {
558                         XPathNavigator nav = CreateNavigator ();
559                         XPathExpression expr = nav.Compile (xpath);
560                         if (nsmgr != null)
561                                 expr.SetContext (nsmgr);
562                         XPathNodeIterator iter = nav.Select (expr);
563                         ArrayList rgNodes = new ArrayList ();
564                         while (iter.MoveNext ())
565                         {
566                                 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
567                         }
568                         return new XmlNodeArrayList (rgNodes);
569                 }
570
571                 public XmlNode SelectSingleNode (string xpath)
572                 {
573                         return SelectSingleNode (xpath, null);
574                 }
575
576                 [MonoTODO]
577                 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
578                 {
579                         XPathNavigator nav = CreateNavigator ();
580                         XPathExpression expr = nav.Compile (xpath);
581                         if (nsmgr != null)
582                                 expr.SetContext (nsmgr);
583                         XPathNodeIterator iter = nav.Select (expr);
584                         if (!iter.MoveNext ())
585                                 return null;
586                         return ((XmlDocumentNavigator) iter.Current).Node;
587                 }
588
589 //              internal void SetParentNode (XmlNode parent)
590 //              {
591 //                      parentNode = parent;
592 //              }
593
594                 [MonoTODO]
595                 public virtual bool Supports (string feature, string version)
596                 {
597                         throw new NotImplementedException ();
598                 }
599
600                 public abstract void WriteContentTo (XmlWriter w);
601
602                 public abstract void WriteTo (XmlWriter w);
603
604                 // It parses this and all the ancestor elements,
605                 // find 'xmlns' declarations, stores and then return them.
606                 // TODO: tests
607                 internal XmlNamespaceManager ConstructNamespaceManager ()
608                 {
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;
615                                 break;
616                         case XmlNodeType.Element:
617                                 el = this as XmlElement;
618                                 break;
619                         default:
620                                 el = this.ParentNode as XmlElement;
621                                 break;
622                         }
623
624                         while(el != null) {
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);
632                                         }
633                                 }
634                                 // When reached to document, then it will set null value :)
635                                 el = el.ParentNode as XmlElement;
636                         }
637                         return nsmgr;
638                 }
639                 #endregion
640         }
641 }