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;
88 while (node != null) {
89 if (node.NodeType == XmlNodeType.Text)
90 builder.Append (node.Value);
91 AppendChildValues (node, builder);
92 node = node.NextSibling;
96 public virtual string InnerXml {
98 StringWriter sw = new StringWriter ();
99 XmlTextWriter xtw = new XmlTextWriter (sw);
101 WriteContentTo (xtw);
103 return sw.GetStringBuilder ().ToString ();
107 throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
111 public virtual bool IsReadOnly {
112 get { return false; }
115 [System.Runtime.CompilerServices.IndexerName("Item")]
116 public virtual XmlElement this [string name] {
118 foreach (XmlNode node in ChildNodes) {
119 if ((node.NodeType == XmlNodeType.Element) &&
120 (node.Name == name)) {
121 return (XmlElement) node;
129 [System.Runtime.CompilerServices.IndexerName("Item")]
130 public virtual XmlElement this [string localname, string ns] {
132 foreach (XmlNode node in ChildNodes) {
133 if ((node.NodeType == XmlNodeType.Element) &&
134 (node.LocalName == localname) &&
135 (node.NamespaceURI == ns)) {
136 return (XmlElement) node;
144 public virtual XmlNode LastChild {
145 get { return LastLinkedChild; }
148 internal virtual XmlLinkedNode LastLinkedChild {
153 public abstract string LocalName { get; }
155 public abstract string Name { get; }
157 public virtual string NamespaceURI {
158 get { return String.Empty; }
161 public virtual XmlNode NextSibling {
165 public abstract XmlNodeType NodeType { get; }
167 internal virtual XPathNodeType XPathNodeType {
169 return (XPathNodeType) (-1);
173 public virtual string OuterXml {
175 StringWriter sw = new StringWriter ();
176 XmlTextWriter xtw = new XmlTextWriter (sw);
180 return sw.GetStringBuilder ().ToString ();
184 public virtual XmlDocument OwnerDocument {
185 get { return ownerDocument; }
188 public virtual XmlNode ParentNode {
189 get { return parentNode; }
192 public virtual string Prefix {
193 get { return String.Empty; }
197 public virtual XmlNode PreviousSibling {
201 public virtual string Value {
203 set { throw new InvalidOperationException ("This node does not have a value"); }
206 internal virtual string XmlLang {
208 if(Attributes != null)
209 foreach(XmlAttribute attr in Attributes)
210 if(attr.Name == "xml:lang")
212 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
216 internal virtual XmlSpace XmlSpace {
218 if(Attributes != null) {
219 foreach(XmlAttribute attr in Attributes) {
220 if(attr.Name == "xml:space") {
222 case "preserve": return XmlSpace.Preserve;
223 case "default": return XmlSpace.Default;
229 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
237 public virtual XmlNode AppendChild (XmlNode newChild)
239 // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
240 return InsertBefore (newChild, null);
243 public virtual XmlNode Clone ()
245 // By MS document, it is equivalent to CloneNode(true).
246 return this.CloneNode (true);
249 public abstract XmlNode CloneNode (bool deep);
252 public XPathNavigator CreateNavigator ()
254 XmlDocument document = this.NodeType == XmlNodeType.Document ?
255 this as XmlDocument : this.ownerDocument;
256 return document.CreateNavigator (this);
259 public IEnumerator GetEnumerator ()
261 return new XmlNodeListChildren (this).GetEnumerator ();
264 [MonoTODO("performance problem.")]
265 public virtual string GetNamespaceOfPrefix (string prefix)
267 XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
268 return nsmgr.LookupNamespace (prefix);
271 [MonoTODO("performance problem.")]
272 public virtual string GetPrefixOfNamespace (string namespaceURI)
274 XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
275 string ns = nsmgr.LookupPrefix (namespaceURI);
276 return (ns != null) ? ns : String.Empty;
279 object ICloneable.Clone ()
284 IEnumerator IEnumerable.GetEnumerator ()
286 return GetEnumerator ();
289 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
291 // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
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;
297 argNode = refChild.NextSibling;
298 else if(ChildNodes.Count > 0)
299 argNode = FirstChild;
300 return InsertBefore (newChild, argNode);
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)
306 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
308 if (NodeType == XmlNodeType.Document ||
309 NodeType == XmlNodeType.Element ||
310 NodeType == XmlNodeType.Attribute ||
311 NodeType == XmlNodeType.DocumentFragment) {
313 throw new ArgumentException ("The specified node is readonly.");
315 if (newChild.OwnerDocument != ownerDoc)
316 throw new ArgumentException ("Can't append a node created by another document.");
318 if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
319 throw new ArgumentException ("argument nodes are on the different documents.");
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.");
326 // checking validity finished. then appending...
328 return insertBeforeIntern (newChild, refChild);
331 throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
334 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
336 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
338 ownerDoc.onNodeInserting (newChild, this);
340 if(newChild.ParentNode != null)
341 newChild.ParentNode.RemoveChild (newChild);
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.)
351 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
352 XmlLinkedNode lastLinkedChild = LastLinkedChild;
354 newLinkedChild.parentNode = this;
356 if(refChild == null) {
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;
368 LastLinkedChild = newLinkedChild;
369 LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
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;
379 LastLinkedChild.NextLinkedSibling = newLinkedChild;
381 prev.NextLinkedSibling = newLinkedChild;
382 newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
384 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
390 public virtual void Normalize ()
392 throw new NotImplementedException ();
395 public virtual XmlNode PrependChild (XmlNode newChild)
397 return InsertAfter (newChild, null);
400 public virtual void RemoveAll ()
402 if (Attributes != null)
403 Attributes.RemoveAll ();
405 for (XmlNode node = FirstChild; node != null; node = next) {
406 next = node.NextSibling;
411 public virtual XmlNode RemoveChild (XmlNode oldChild)
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.");
417 ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
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));
426 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
428 if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
429 // If there is only one children, simply clear.
430 LastLinkedChild = null;
432 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
433 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
434 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
436 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
437 Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
438 beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
440 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
441 throw new ArgumentException ();
443 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
445 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
446 if (oldLinkedChild.NextLinkedSibling == firstChild)
447 this.LastLinkedChild = beforeLinkedChild;
449 oldLinkedChild.NextLinkedSibling = null;
452 ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
453 oldChild.parentNode = null; // clear parent 'after' above logic.
458 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
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;
468 foreach(XmlNode n in ChildNodes) {
470 XmlNode prev = oldChild.PreviousSibling;
471 RemoveChild (oldChild);
472 InsertAfter (newChild, prev);
479 public XmlNodeList SelectNodes (string xpath)
481 return SelectNodes (xpath, null);
485 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
487 XPathNavigator nav = CreateNavigator ();
488 XPathExpression expr = nav.Compile (xpath);
490 expr.SetContext (nsmgr);
491 XPathNodeIterator iter = nav.Select (expr);
492 ArrayList rgNodes = new ArrayList ();
493 while (iter.MoveNext ())
495 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
497 return new XmlNodeArrayList (rgNodes);
500 public XmlNode SelectSingleNode (string xpath)
502 return SelectSingleNode (xpath, null);
506 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
508 XPathNavigator nav = CreateNavigator ();
509 XPathExpression expr = nav.Compile (xpath);
511 expr.SetContext (nsmgr);
512 XPathNodeIterator iter = nav.Select (expr);
513 if (!iter.MoveNext ())
515 return ((XmlDocumentNavigator) iter.Current).Node;
518 internal void SetParentNode (XmlNode parent)
524 public virtual bool Supports (string feature, string version)
526 throw new NotImplementedException ();
529 public abstract void WriteContentTo (XmlWriter w);
531 public abstract void WriteTo (XmlWriter w);
533 // It parses this and all the ancestor elements,
534 // find 'xmlns' declarations, stores and then return them.
536 internal XmlNamespaceManager ConstructNamespaceManager ()
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;
545 case XmlNodeType.Element:
546 el = this as XmlElement;
549 el = this.ParentNode as XmlElement;
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);
563 // When reached to document, then it will set null value :)
564 el = el.ParentNode as XmlElement;