2003-04-27 Pedro Mart�nez Juli� <yoros@wanadoo.es>
[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                                 string result = (ParentNode != null) ? ParentNode.BaseURI : OwnerDocument.BaseURI;
49                                 try {
50                                         Uri test = new Uri(result);
51                                 }
52                                 catch {
53                                         result = "file://" + result;
54                                 }
55                                 return result;
56                         }
57                 }
58
59                 public virtual XmlNodeList ChildNodes {
60                         get {
61                                 return new XmlNodeListChildren (this);
62                         }
63                 }
64
65                 public virtual XmlNode FirstChild {
66                         get {
67                                 if (LastChild != null) {
68                                         return LastLinkedChild.NextLinkedSibling;
69                                 }
70                                 else {
71                                         return null;
72                                 }
73                         }
74                 }
75
76                 public virtual bool HasChildNodes {
77                         get { return LastChild != null; }
78                 }
79
80                 [MonoTODO("confirm whether this way is right for each not-overriden types.")]
81                 public virtual string InnerText {
82                         get {
83                                 StringBuilder builder = new StringBuilder ();
84                                 AppendChildValues (this, builder);
85                                 return builder.ToString ();
86                         }
87
88                         set { throw new NotImplementedException (); }
89                 }
90
91                 private void AppendChildValues (XmlNode parent, StringBuilder builder)
92                 {
93                         XmlNode node = parent.FirstChild;
94
95                         while (node != null) {
96                                 if (node.NodeType == XmlNodeType.Text)
97                                         builder.Append (node.Value);
98                                 AppendChildValues (node, builder);
99                                 node = node.NextSibling;
100                         }
101                 }
102
103                 [MonoTODO("Setter.")]
104                 public virtual string InnerXml {
105                         get {
106                                 StringWriter sw = new StringWriter ();
107                                 XmlTextWriter xtw = new XmlTextWriter (sw);
108
109                                 WriteContentTo (xtw);
110
111                                 return sw.GetStringBuilder ().ToString ();
112                         }
113
114                         set { throw new NotImplementedException (); }
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                                 return (XPathNodeType) (-1);
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.GetStringBuilder ().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                         return new XmlDocumentNavigator (this);
261                 }
262
263                 public IEnumerator GetEnumerator ()
264                 {
265                         return new XmlNodeListChildren (this).GetEnumerator ();
266                 }
267
268                 [MonoTODO("performance problem.")]
269                 public virtual string GetNamespaceOfPrefix (string prefix)
270                 {
271                         XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
272                         return nsmgr.LookupNamespace (prefix);
273                 }
274
275                 [MonoTODO("performance problem.")]
276                 public virtual string GetPrefixOfNamespace (string namespaceURI)
277                 {
278                         XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
279                         string ns = nsmgr.LookupPrefix (namespaceURI);
280                         return (ns != null) ? ns : String.Empty;
281                 }
282
283                 object ICloneable.Clone ()
284                 {
285                         return Clone ();
286                 }
287
288                 IEnumerator IEnumerable.GetEnumerator ()
289                 {
290                         return GetEnumerator ();
291                 }
292
293                 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
294                 {
295                         // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
296
297                         // I took this way because rather than calling InsertAfter() from InsertBefore()
298                         //   because current implementation of 'NextSibling' looks faster than 'PreviousSibling'.
299                         XmlNode argNode = null;
300                         if(refChild != null)
301                                 argNode = refChild.NextSibling;
302                         else if(ChildNodes.Count > 0)
303                                 argNode = FirstChild;
304                         return InsertBefore (newChild, argNode);
305                 }
306
307                 [MonoTODO("If inserted node is entity reference, then check conforming entity. Wait for DTD implementation.")]
308                 public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
309                 {
310                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
311
312                         if (NodeType == XmlNodeType.Document ||
313                             NodeType == XmlNodeType.Element ||
314                             NodeType == XmlNodeType.Attribute ||
315                             NodeType == XmlNodeType.DocumentFragment) {
316                                 if (IsReadOnly)
317                                         throw new ArgumentException ("The specified node is readonly.");
318
319                                 if (newChild.OwnerDocument != ownerDoc)
320                                         throw new ArgumentException ("Can't append a node created by another document.");
321
322                                 if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
323                                                 throw new ArgumentException ("argument nodes are on the different documents.");
324
325                                 // This check is done by MS.NET 1.0, but isn't done for MS.NET 1.1. 
326                                 // Skip this check in the meantime...
327 //                              if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement))
328 //                                      throw new XmlException ("multiple document element not allowed.");
329
330                                 // checking validity finished. then appending...
331
332                                 return insertBeforeIntern (newChild, refChild);
333                         } 
334                         else
335                                 throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
336                 }
337
338                 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
339                 {
340                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
341
342                         ownerDoc.onNodeInserting (newChild, this);
343
344                         if(newChild.ParentNode != null)
345                                 newChild.ParentNode.RemoveChild (newChild);
346
347                         if(newChild.NodeType == XmlNodeType.DocumentFragment) {
348                                 int x = newChild.ChildNodes.Count;
349                                 for(int i=0; i<x; i++) {
350                                         XmlNode n = newChild.ChildNodes [0];
351                                         this.InsertBefore (n, refChild);        // recursively invokes events. (It is compatible with MS implementation.)
352                                 }
353                         }
354                         else {
355                                 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
356                                 XmlLinkedNode lastLinkedChild = LastLinkedChild;
357
358                                 newLinkedChild.parentNode = this;
359
360                                 if(refChild == null) {
361                                         // append last, so:
362                                         // * set nextSibling of previous lastchild to newChild
363                                         // * set lastchild = newChild
364                                         // * set next of newChild to firstChild
365                                         if(LastLinkedChild != null) {
366                                                 XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
367                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;
368                                                 LastLinkedChild = newLinkedChild;
369                                                 newLinkedChild.NextLinkedSibling = formerFirst;
370                                         }
371                                         else {
372                                                 LastLinkedChild = newLinkedChild;
373                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;     // FirstChild
374                                         }
375                                 }
376                                 else {
377                                         // append not last, so:
378                                         // * if newchild is first, then set next of lastchild is newChild.
379                                         //   otherwise, set next of previous sibling to newChild
380                                         // * set next of newChild to refChild
381                                         XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
382                                         if(prev == null)
383                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;
384                                         else
385                                                 prev.NextLinkedSibling = newLinkedChild;
386                                         newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
387                                 }
388                                 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
389                         }
390                         return newChild;
391                 }
392
393                 [MonoTODO]
394                 public virtual void Normalize ()
395                 {
396                         throw new NotImplementedException ();
397                 }
398
399                 public virtual XmlNode PrependChild (XmlNode newChild)
400                 {
401                         return InsertAfter (newChild, null);
402                 }
403
404                 public virtual void RemoveAll ()
405                 {
406                         XmlNode next = null;
407                         for (XmlNode node = FirstChild; node != null; node = next) {
408                                 next = node.NextSibling;
409                                 RemoveChild (node);
410                         }
411                 }
412
413                 public virtual XmlNode RemoveChild (XmlNode oldChild)
414                 {
415                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
416                         if(oldChild.ParentNode != this)
417                                 throw new XmlException ("specified child is not child of this node.");
418
419                         ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
420
421                         if (NodeType != XmlNodeType.Attribute && 
422                                 NodeType != XmlNodeType.Element && 
423                                 NodeType != XmlNodeType.Document && 
424                                 NodeType != XmlNodeType.DocumentFragment)
425                                 throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
426
427                         if (IsReadOnly)
428                                 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
429
430                         if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
431                                 // If there is only one children, simply clear.
432                                 LastLinkedChild = null;
433                         else {
434                                 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
435                                 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
436                                 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
437                                 
438                                 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false && 
439                                         Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
440                                         beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
441
442                                 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
443                                         throw new ArgumentException ();
444
445                                 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
446
447                                 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
448                                 if (oldLinkedChild.NextLinkedSibling == firstChild)
449                                         this.LastLinkedChild = beforeLinkedChild;
450
451                                 oldLinkedChild.NextLinkedSibling = null;
452                                 }
453
454                         ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
455                         oldChild.parentNode = null;     // clear parent 'after' above logic.
456
457                         return oldChild;
458                 }
459
460                 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
461                 {
462                         if(oldChild.ParentNode != this)
463                                 throw new InvalidOperationException ("oldChild is not a child of this node.");
464                         XmlNode parent = this.ParentNode;
465                         while(parent != null) {
466                                 if(newChild == parent)
467                                         throw new InvalidOperationException ("newChild is ancestor of this node.");
468                                 parent = parent.ParentNode;
469                         }
470                         foreach(XmlNode n in ChildNodes) {
471                                 if(n == oldChild) {
472                                         XmlNode prev = oldChild.PreviousSibling;
473                                         RemoveChild (oldChild);
474                                         InsertAfter (newChild, prev);
475                                         break;
476                                 }
477                         }
478                         return oldChild;
479                 }
480
481                 public XmlNodeList SelectNodes (string xpath)
482                 {
483                         return SelectNodes (xpath, null);
484                 }
485
486                 [MonoTODO]
487                 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
488                 {
489                         XPathNavigator nav = CreateNavigator ();
490                         XPathExpression expr = nav.Compile (xpath);
491                         if (nsmgr != null)
492                                 expr.SetContext (nsmgr);
493                         XPathNodeIterator iter = nav.Select (expr);
494                         ArrayList rgNodes = new ArrayList ();
495                         while (iter.MoveNext ())
496                         {
497                                 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
498                         }
499                         return new XmlNodeArrayList (rgNodes);
500                 }
501
502                 public XmlNode SelectSingleNode (string xpath)
503                 {
504                         return SelectSingleNode (xpath, null);
505                 }
506
507                 [MonoTODO]
508                 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
509                 {
510                         XPathNavigator nav = CreateNavigator ();
511                         XPathExpression expr = nav.Compile (xpath);
512                         if (nsmgr != null)
513                                 expr.SetContext (nsmgr);
514                         XPathNodeIterator iter = nav.Select (expr);
515                         if (!iter.MoveNext ())
516                                 return null;
517                         return ((XmlDocumentNavigator) iter.Current).Node;
518                 }
519
520                 internal void SetParentNode (XmlNode parent)
521                 {
522                         parentNode = parent;
523                 }
524
525                 [MonoTODO]
526                 public virtual bool Supports (string feature, string version)
527                 {
528                         throw new NotImplementedException ();
529                 }
530
531                 public abstract void WriteContentTo (XmlWriter w);
532
533                 public abstract void WriteTo (XmlWriter w);
534
535                 // It parses this and all the ancestor elements,
536                 // find 'xmlns' declarations, stores and then return them.
537                 // TODO: tests
538                 internal XmlNamespaceManager ConstructNamespaceManager ()
539                 {
540                         XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
541                         XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
542                         XmlElement el = null;
543                         switch(this.NodeType) {
544                         case XmlNodeType.Attribute:
545                                 el = ((XmlAttribute)this).OwnerElement;
546                                 break;
547                         case XmlNodeType.Element:
548                                 el = this as XmlElement;
549                                 break;
550                         default:
551                                 el = this.ParentNode as XmlElement;
552                                 break;
553                         }
554
555                         while(el != null) {
556                                 foreach(XmlAttribute attr in el.Attributes) {
557                                         if(attr.Prefix == "xmlns") {
558                                                 if (nsmgr.LookupNamespace (attr.LocalName) == null)
559                                                         nsmgr.AddNamespace (attr.LocalName, attr.Value);
560                                         } else if(attr.Name == "xmlns") {
561                                                 if(nsmgr.LookupNamespace (String.Empty) == null)
562                                                         nsmgr.AddNamespace (String.Empty, attr.Value);
563                                         }
564                                 }
565                                 // When reached to document, then it will set null value :)
566                                 el = el.ParentNode as XmlElement;
567                         }
568                         return nsmgr;
569                 }
570                 #endregion
571         }
572 }