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 string result = (ParentNode != null) ? ParentNode.BaseURI : OwnerDocument.BaseURI;
50 Uri test = new Uri(result);
53 result = "file://" + result;
59 public virtual XmlNodeList ChildNodes {
61 return new XmlNodeListChildren (this);
65 public virtual XmlNode FirstChild {
67 if (LastChild != null) {
68 return LastLinkedChild.NextLinkedSibling;
76 public virtual bool HasChildNodes {
77 get { return LastChild != null; }
80 [MonoTODO("confirm whether this way is right for each not-overriden types.")]
81 public virtual string InnerText {
83 StringBuilder builder = new StringBuilder ();
84 AppendChildValues (this, builder);
85 return builder.ToString ();
88 set { throw new NotImplementedException (); }
91 private void AppendChildValues (XmlNode parent, StringBuilder builder)
93 XmlNode node = parent.FirstChild;
95 while (node != null) {
96 if (node.NodeType == XmlNodeType.Text)
97 builder.Append (node.Value);
98 AppendChildValues (node, builder);
99 node = node.NextSibling;
103 [MonoTODO("Setter.")]
104 public virtual string InnerXml {
106 StringWriter sw = new StringWriter ();
107 XmlTextWriter xtw = new XmlTextWriter (sw);
109 WriteContentTo (xtw);
111 return sw.GetStringBuilder ().ToString ();
114 set { throw new NotImplementedException (); }
117 public virtual bool IsReadOnly {
118 get { return false; }
121 [System.Runtime.CompilerServices.IndexerName("Item")]
122 public virtual XmlElement this [string name] {
124 foreach (XmlNode node in ChildNodes) {
125 if ((node.NodeType == XmlNodeType.Element) &&
126 (node.Name == name)) {
127 return (XmlElement) node;
135 [System.Runtime.CompilerServices.IndexerName("Item")]
136 public virtual XmlElement this [string localname, string ns] {
138 foreach (XmlNode node in ChildNodes) {
139 if ((node.NodeType == XmlNodeType.Element) &&
140 (node.LocalName == localname) &&
141 (node.NamespaceURI == ns)) {
142 return (XmlElement) node;
150 public virtual XmlNode LastChild {
151 get { return LastLinkedChild; }
154 internal virtual XmlLinkedNode LastLinkedChild {
159 public abstract string LocalName { get; }
161 public abstract string Name { get; }
163 public virtual string NamespaceURI {
164 get { return String.Empty; }
167 public virtual XmlNode NextSibling {
171 public abstract XmlNodeType NodeType { get; }
173 internal virtual XPathNodeType XPathNodeType {
175 return (XPathNodeType) (-1);
179 public virtual string OuterXml {
181 StringWriter sw = new StringWriter ();
182 XmlTextWriter xtw = new XmlTextWriter (sw);
186 return sw.GetStringBuilder ().ToString ();
190 public virtual XmlDocument OwnerDocument {
191 get { return ownerDocument; }
194 public virtual XmlNode ParentNode {
195 get { return parentNode; }
198 public virtual string Prefix {
199 get { return String.Empty; }
203 public virtual XmlNode PreviousSibling {
207 public virtual string Value {
209 set { throw new InvalidOperationException ("This node does not have a value"); }
212 internal virtual string XmlLang {
214 if(Attributes != null)
215 foreach(XmlAttribute attr in Attributes)
216 if(attr.Name == "xml:lang")
218 return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
222 internal virtual XmlSpace XmlSpace {
224 if(Attributes != null) {
225 foreach(XmlAttribute attr in Attributes) {
226 if(attr.Name == "xml:space") {
228 case "preserve": return XmlSpace.Preserve;
229 case "default": return XmlSpace.Default;
235 return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
243 public virtual XmlNode AppendChild (XmlNode newChild)
245 // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
246 return InsertBefore (newChild, null);
249 public virtual XmlNode Clone ()
251 // By MS document, it is equivalent to CloneNode(true).
252 return this.CloneNode (true);
255 public abstract XmlNode CloneNode (bool deep);
258 public XPathNavigator CreateNavigator ()
260 return new XmlDocumentNavigator (this);
263 public IEnumerator GetEnumerator ()
265 return new XmlNodeListChildren (this).GetEnumerator ();
268 [MonoTODO("performance problem.")]
269 public virtual string GetNamespaceOfPrefix (string prefix)
271 XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
272 return nsmgr.LookupNamespace (prefix);
275 [MonoTODO("performance problem.")]
276 public virtual string GetPrefixOfNamespace (string namespaceURI)
278 XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
279 string ns = nsmgr.LookupPrefix (namespaceURI);
280 return (ns != null) ? ns : String.Empty;
283 object ICloneable.Clone ()
288 IEnumerator IEnumerable.GetEnumerator ()
290 return GetEnumerator ();
293 public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
295 // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
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;
301 argNode = refChild.NextSibling;
302 else if(ChildNodes.Count > 0)
303 argNode = FirstChild;
304 return InsertBefore (newChild, argNode);
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)
310 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
312 if (NodeType == XmlNodeType.Document ||
313 NodeType == XmlNodeType.Element ||
314 NodeType == XmlNodeType.Attribute ||
315 NodeType == XmlNodeType.DocumentFragment) {
317 throw new ArgumentException ("The specified node is readonly.");
319 if (newChild.OwnerDocument != ownerDoc)
320 throw new ArgumentException ("Can't append a node created by another document.");
322 if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
323 throw new ArgumentException ("argument nodes are on the different documents.");
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.");
330 // checking validity finished. then appending...
332 return insertBeforeIntern (newChild, refChild);
335 throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
338 internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
340 XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
342 ownerDoc.onNodeInserting (newChild, this);
344 if(newChild.ParentNode != null)
345 newChild.ParentNode.RemoveChild (newChild);
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.)
355 XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
356 XmlLinkedNode lastLinkedChild = LastLinkedChild;
358 newLinkedChild.parentNode = this;
360 if(refChild == null) {
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;
372 LastLinkedChild = newLinkedChild;
373 LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
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;
383 LastLinkedChild.NextLinkedSibling = newLinkedChild;
385 prev.NextLinkedSibling = newLinkedChild;
386 newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
388 ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
394 public virtual void Normalize ()
396 throw new NotImplementedException ();
399 public virtual XmlNode PrependChild (XmlNode newChild)
401 return InsertAfter (newChild, null);
404 public virtual void RemoveAll ()
407 for (XmlNode node = FirstChild; node != null; node = next) {
408 next = node.NextSibling;
413 public virtual XmlNode RemoveChild (XmlNode oldChild)
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.");
419 ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
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));
428 throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
430 if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
431 // If there is only one children, simply clear.
432 LastLinkedChild = null;
434 XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
435 XmlLinkedNode beforeLinkedChild = LastLinkedChild;
436 XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
438 while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
439 Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
440 beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
442 if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
443 throw new ArgumentException ();
445 beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
447 // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
448 if (oldLinkedChild.NextLinkedSibling == firstChild)
449 this.LastLinkedChild = beforeLinkedChild;
451 oldLinkedChild.NextLinkedSibling = null;
454 ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
455 oldChild.parentNode = null; // clear parent 'after' above logic.
460 public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
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;
470 foreach(XmlNode n in ChildNodes) {
472 XmlNode prev = oldChild.PreviousSibling;
473 RemoveChild (oldChild);
474 InsertAfter (newChild, prev);
481 public XmlNodeList SelectNodes (string xpath)
483 return SelectNodes (xpath, null);
487 public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
489 XPathNavigator nav = CreateNavigator ();
490 XPathExpression expr = nav.Compile (xpath);
492 expr.SetContext (nsmgr);
493 XPathNodeIterator iter = nav.Select (expr);
494 ArrayList rgNodes = new ArrayList ();
495 while (iter.MoveNext ())
497 rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
499 return new XmlNodeArrayList (rgNodes);
502 public XmlNode SelectSingleNode (string xpath)
504 return SelectSingleNode (xpath, null);
508 public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
510 XPathNavigator nav = CreateNavigator ();
511 XPathExpression expr = nav.Compile (xpath);
513 expr.SetContext (nsmgr);
514 XPathNodeIterator iter = nav.Select (expr);
515 if (!iter.MoveNext ())
517 return ((XmlDocumentNavigator) iter.Current).Node;
520 internal void SetParentNode (XmlNode parent)
526 public virtual bool Supports (string feature, string version)
528 throw new NotImplementedException ();
531 public abstract void WriteContentTo (XmlWriter w);
533 public abstract void WriteTo (XmlWriter w);
535 // It parses this and all the ancestor elements,
536 // find 'xmlns' declarations, stores and then return them.
538 internal XmlNamespaceManager ConstructNamespaceManager ()
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;
547 case XmlNodeType.Element:
548 el = this as XmlElement;
551 el = this.ParentNode as XmlElement;
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);
565 // When reached to document, then it will set null value :)
566 el = el.ParentNode as XmlElement;