2003-05-24 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;
87
88                         while (node != null) {
89                                 if (node.NodeType == XmlNodeType.Text)
90                                         builder.Append (node.Value);
91                                 AppendChildValues (node, builder);
92                                 node = node.NextSibling;
93                         }
94                 }
95
96                 public virtual string InnerXml {
97                         get {
98                                 StringWriter sw = new StringWriter ();
99                                 XmlTextWriter xtw = new XmlTextWriter (sw);
100
101                                 WriteContentTo (xtw);
102
103                                 return sw.GetStringBuilder ().ToString ();
104                         }
105
106                         set {
107                                 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
108                         }
109                 }
110
111                 public virtual bool IsReadOnly {
112                         get { return false; }
113                 }
114
115                 [System.Runtime.CompilerServices.IndexerName("Item")]
116                 public virtual XmlElement this [string name] {
117                         get { 
118                                 foreach (XmlNode node in ChildNodes) {
119                                         if ((node.NodeType == XmlNodeType.Element) &&
120                                             (node.Name == name)) {
121                                                 return (XmlElement) node;
122                                         }
123                                 }
124
125                                 return null;
126                         }
127                 }
128
129                 [System.Runtime.CompilerServices.IndexerName("Item")]
130                 public virtual XmlElement this [string localname, string ns] {
131                         get { 
132                                 foreach (XmlNode node in ChildNodes) {
133                                         if ((node.NodeType == XmlNodeType.Element) &&
134                                             (node.LocalName == localname) && 
135                                             (node.NamespaceURI == ns)) {
136                                                 return (XmlElement) node;
137                                         }
138                                 }
139
140                                 return null;
141                         }
142                 }
143
144                 public virtual XmlNode LastChild {
145                         get { return LastLinkedChild; }
146                 }
147
148                 internal virtual XmlLinkedNode LastLinkedChild {
149                         get { return null; }
150                         set { }
151                 }
152
153                 public abstract string LocalName { get; }
154
155                 public abstract string Name     { get; }
156
157                 public virtual string NamespaceURI {
158                         get { return String.Empty; }
159                 }
160
161                 public virtual XmlNode NextSibling {
162                         get { return null; }
163                 }
164
165                 public abstract XmlNodeType NodeType { get;     }
166
167                 internal virtual XPathNodeType XPathNodeType {
168                         get {
169                                 return (XPathNodeType) (-1);
170                         }
171                 }
172
173                 public virtual string OuterXml {
174                         get {
175                                 StringWriter sw = new StringWriter ();
176                                 XmlTextWriter xtw = new XmlTextWriter (sw);
177
178                                 WriteTo (xtw);
179
180                                 return sw.GetStringBuilder ().ToString ();
181                         }
182                 }
183
184                 public virtual XmlDocument OwnerDocument {
185                         get { return ownerDocument; }
186                 }
187
188                 public virtual XmlNode ParentNode {
189                         get { return parentNode; }
190                 }
191
192                 public virtual string Prefix {
193                         get { return String.Empty; }
194                         set {}
195                 }
196
197                 public virtual XmlNode PreviousSibling {
198                         get { return null; }
199                 }
200
201                 public virtual string Value {
202                         get { return null; }
203                         set { throw new InvalidOperationException ("This node does not have a value"); }
204                 }
205
206                 internal virtual string XmlLang {
207                         get {
208                                 if(Attributes != null)
209                                         foreach(XmlAttribute attr in Attributes)
210                                                 if(attr.Name == "xml:lang")
211                                                         return attr.Value;
212                                 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
213                         }
214                 }
215
216                 internal virtual XmlSpace XmlSpace {
217                         get {
218                                 if(Attributes != null) {
219                                         foreach(XmlAttribute attr in Attributes) {
220                                                 if(attr.Name == "xml:space") {
221                                                         switch(attr.Value) {
222                                                         case "preserve": return XmlSpace.Preserve;
223                                                         case "default": return XmlSpace.Default;
224                                                         }
225                                                         break;
226                                                 }
227                                         }
228                                 }
229                                 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
230                         }
231                 }
232
233                 #endregion
234
235                 #region Methods
236
237                 public virtual XmlNode AppendChild (XmlNode newChild)
238                 {
239                         // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
240                         return InsertBefore (newChild, null);
241                 }
242
243                 public virtual XmlNode Clone ()
244                 {
245                         // By MS document, it is equivalent to CloneNode(true).
246                         return this.CloneNode (true);
247                 }
248
249                 public abstract XmlNode CloneNode (bool deep);
250
251                 [MonoTODO]
252                 public XPathNavigator CreateNavigator ()
253                 {
254                         XmlDocument document = this.NodeType == XmlNodeType.Document ?
255                                 this as XmlDocument : this.ownerDocument;
256                         return document.CreateNavigator (this);
257                 }
258
259                 public IEnumerator GetEnumerator ()
260                 {
261                         return new XmlNodeListChildren (this).GetEnumerator ();
262                 }
263
264                 [MonoTODO("performance problem.")]
265                 public virtual string GetNamespaceOfPrefix (string prefix)
266                 {
267                         XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
268                         return nsmgr.LookupNamespace (prefix);
269                 }
270
271                 [MonoTODO("performance problem.")]
272                 public virtual string GetPrefixOfNamespace (string namespaceURI)
273                 {
274                         XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
275                         string ns = nsmgr.LookupPrefix (namespaceURI);
276                         return (ns != null) ? ns : String.Empty;
277                 }
278
279                 object ICloneable.Clone ()
280                 {
281                         return Clone ();
282                 }
283
284                 IEnumerator IEnumerable.GetEnumerator ()
285                 {
286                         return GetEnumerator ();
287                 }
288
289                 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
290                 {
291                         // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
292
293                         // I took this way because rather than calling InsertAfter() from InsertBefore()
294                         //   because current implementation of 'NextSibling' looks faster than 'PreviousSibling'.
295                         XmlNode argNode = null;
296                         if(refChild != null)
297                                 argNode = refChild.NextSibling;
298                         else if(ChildNodes.Count > 0)
299                                 argNode = FirstChild;
300                         return InsertBefore (newChild, argNode);
301                 }
302
303                 [MonoTODO("If inserted node is entity reference, then check conforming entity. Wait for DTD implementation.")]
304                 public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
305                 {
306                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
307
308                         if (NodeType == XmlNodeType.Document ||
309                             NodeType == XmlNodeType.Element ||
310                             NodeType == XmlNodeType.Attribute ||
311                             NodeType == XmlNodeType.DocumentFragment) {
312                                 if (IsReadOnly)
313                                         throw new ArgumentException ("The specified node is readonly.");
314
315                                 if (newChild.OwnerDocument != ownerDoc)
316                                         throw new ArgumentException ("Can't append a node created by another document.");
317
318                                 if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
319                                                 throw new ArgumentException ("argument nodes are on the different documents.");
320
321                                 // This check is done by MS.NET 1.0, but isn't done for MS.NET 1.1. 
322                                 // Skip this check in the meantime...
323 //                              if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement))
324 //                                      throw new XmlException ("multiple document element not allowed.");
325
326                                 // checking validity finished. then appending...
327
328                                 return insertBeforeIntern (newChild, refChild);
329                         } 
330                         else
331                                 throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
332                 }
333
334                 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
335                 {
336                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
337
338                         ownerDoc.onNodeInserting (newChild, this);
339
340                         if(newChild.ParentNode != null)
341                                 newChild.ParentNode.RemoveChild (newChild);
342
343                         if(newChild.NodeType == XmlNodeType.DocumentFragment) {
344                                 int x = newChild.ChildNodes.Count;
345                                 for(int i=0; i<x; i++) {
346                                         XmlNode n = newChild.ChildNodes [0];
347                                         this.InsertBefore (n, refChild);        // recursively invokes events. (It is compatible with MS implementation.)
348                                 }
349                         }
350                         else {
351                                 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
352                                 XmlLinkedNode lastLinkedChild = LastLinkedChild;
353
354                                 newLinkedChild.parentNode = this;
355
356                                 if(refChild == null) {
357                                         // append last, so:
358                                         // * set nextSibling of previous lastchild to newChild
359                                         // * set lastchild = newChild
360                                         // * set next of newChild to firstChild
361                                         if(LastLinkedChild != null) {
362                                                 XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
363                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;
364                                                 LastLinkedChild = newLinkedChild;
365                                                 newLinkedChild.NextLinkedSibling = formerFirst;
366                                         }
367                                         else {
368                                                 LastLinkedChild = newLinkedChild;
369                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;     // FirstChild
370                                         }
371                                 }
372                                 else {
373                                         // append not last, so:
374                                         // * if newchild is first, then set next of lastchild is newChild.
375                                         //   otherwise, set next of previous sibling to newChild
376                                         // * set next of newChild to refChild
377                                         XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
378                                         if(prev == null)
379                                                 LastLinkedChild.NextLinkedSibling = newLinkedChild;
380                                         else
381                                                 prev.NextLinkedSibling = newLinkedChild;
382                                         newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
383                                 }
384                                 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
385                         }
386                         return newChild;
387                 }
388
389                 [MonoTODO]
390                 public virtual void Normalize ()
391                 {
392                         throw new NotImplementedException ();
393                 }
394
395                 public virtual XmlNode PrependChild (XmlNode newChild)
396                 {
397                         return InsertAfter (newChild, null);
398                 }
399
400                 public virtual void RemoveAll ()
401                 {
402                         if (Attributes != null)
403                                 Attributes.RemoveAll ();
404                         XmlNode next = null;
405                         for (XmlNode node = FirstChild; node != null; node = next) {
406                                 next = node.NextSibling;
407                                 RemoveChild (node);
408                         }
409                 }
410
411                 public virtual XmlNode RemoveChild (XmlNode oldChild)
412                 {
413                         XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
414                         if(oldChild.ParentNode != this)
415                                 throw new XmlException ("specified child is not child of this node.");
416
417                         ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
418
419                         if (NodeType != XmlNodeType.Attribute && 
420                                 NodeType != XmlNodeType.Element && 
421                                 NodeType != XmlNodeType.Document && 
422                                 NodeType != XmlNodeType.DocumentFragment)
423                                 throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
424
425                         if (IsReadOnly)
426                                 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
427
428                         if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
429                                 // If there is only one children, simply clear.
430                                 LastLinkedChild = null;
431                         else {
432                                 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
433                                 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
434                                 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
435                                 
436                                 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false && 
437                                         Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
438                                         beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
439
440                                 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
441                                         throw new ArgumentException ();
442
443                                 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
444
445                                 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
446                                 if (oldLinkedChild.NextLinkedSibling == firstChild)
447                                         this.LastLinkedChild = beforeLinkedChild;
448
449                                 oldLinkedChild.NextLinkedSibling = null;
450                                 }
451
452                         ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
453                         oldChild.parentNode = null;     // clear parent 'after' above logic.
454
455                         return oldChild;
456                 }
457
458                 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
459                 {
460                         if(oldChild.ParentNode != this)
461                                 throw new InvalidOperationException ("oldChild is not a child of this node.");
462                         XmlNode parent = this.ParentNode;
463                         while(parent != null) {
464                                 if(newChild == parent)
465                                         throw new InvalidOperationException ("newChild is ancestor of this node.");
466                                 parent = parent.ParentNode;
467                         }
468                         foreach(XmlNode n in ChildNodes) {
469                                 if(n == oldChild) {
470                                         XmlNode prev = oldChild.PreviousSibling;
471                                         RemoveChild (oldChild);
472                                         InsertAfter (newChild, prev);
473                                         break;
474                                 }
475                         }
476                         return oldChild;
477                 }
478
479                 public XmlNodeList SelectNodes (string xpath)
480                 {
481                         return SelectNodes (xpath, null);
482                 }
483
484                 [MonoTODO]
485                 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
486                 {
487                         XPathNavigator nav = CreateNavigator ();
488                         XPathExpression expr = nav.Compile (xpath);
489                         if (nsmgr != null)
490                                 expr.SetContext (nsmgr);
491                         XPathNodeIterator iter = nav.Select (expr);
492                         ArrayList rgNodes = new ArrayList ();
493                         while (iter.MoveNext ())
494                         {
495                                 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
496                         }
497                         return new XmlNodeArrayList (rgNodes);
498                 }
499
500                 public XmlNode SelectSingleNode (string xpath)
501                 {
502                         return SelectSingleNode (xpath, null);
503                 }
504
505                 [MonoTODO]
506                 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
507                 {
508                         XPathNavigator nav = CreateNavigator ();
509                         XPathExpression expr = nav.Compile (xpath);
510                         if (nsmgr != null)
511                                 expr.SetContext (nsmgr);
512                         XPathNodeIterator iter = nav.Select (expr);
513                         if (!iter.MoveNext ())
514                                 return null;
515                         return ((XmlDocumentNavigator) iter.Current).Node;
516                 }
517
518                 internal void SetParentNode (XmlNode parent)
519                 {
520                         parentNode = parent;
521                 }
522
523                 [MonoTODO]
524                 public virtual bool Supports (string feature, string version)
525                 {
526                         throw new NotImplementedException ();
527                 }
528
529                 public abstract void WriteContentTo (XmlWriter w);
530
531                 public abstract void WriteTo (XmlWriter w);
532
533                 // It parses this and all the ancestor elements,
534                 // find 'xmlns' declarations, stores and then return them.
535                 // TODO: tests
536                 internal XmlNamespaceManager ConstructNamespaceManager ()
537                 {
538                         XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
539                         XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
540                         XmlElement el = null;
541                         switch(this.NodeType) {
542                         case XmlNodeType.Attribute:
543                                 el = ((XmlAttribute)this).OwnerElement;
544                                 break;
545                         case XmlNodeType.Element:
546                                 el = this as XmlElement;
547                                 break;
548                         default:
549                                 el = this.ParentNode as XmlElement;
550                                 break;
551                         }
552
553                         while(el != null) {
554                                 foreach(XmlAttribute attr in el.Attributes) {
555                                         if(attr.Prefix == "xmlns") {
556                                                 if (nsmgr.LookupNamespace (attr.LocalName) == null)
557                                                         nsmgr.AddNamespace (attr.LocalName, attr.Value);
558                                         } else if(attr.Name == "xmlns") {
559                                                 if(nsmgr.LookupNamespace (String.Empty) == null)
560                                                         nsmgr.AddNamespace (String.Empty, attr.Value);
561                                         }
562                                 }
563                                 // When reached to document, then it will set null value :)
564                                 el = el.ParentNode as XmlElement;
565                         }
566                         return nsmgr;
567                 }
568                 #endregion
569         }
570 }