XmlNode.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. //
  2. // System.Xml.XmlNode
  3. //
  4. // Author:
  5. // Kral Ferch <[email protected]>
  6. //
  7. // (C) 2002 Kral Ferch
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.IO;
  12. using System.Text;
  13. using System.Xml.XPath;
  14. namespace System.Xml
  15. {
  16. public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
  17. {
  18. #region Fields
  19. XmlDocument ownerDocument;
  20. XmlNode parentNode;
  21. #endregion
  22. #region Constructors
  23. internal XmlNode (XmlDocument ownerDocument)
  24. {
  25. this.ownerDocument = ownerDocument;
  26. }
  27. #endregion
  28. #region Properties
  29. public virtual XmlAttributeCollection Attributes
  30. {
  31. get { return null; }
  32. }
  33. public virtual string BaseURI
  34. {
  35. get { return ParentNode.BaseURI; }
  36. }
  37. public virtual XmlNodeList ChildNodes {
  38. get {
  39. return new XmlNodeListChildren(this);
  40. }
  41. }
  42. public virtual XmlNode FirstChild {
  43. get {
  44. if (LastChild != null) {
  45. return LastLinkedChild.NextLinkedSibling;
  46. }
  47. else {
  48. return null;
  49. }
  50. }
  51. }
  52. public virtual bool HasChildNodes {
  53. get { return LastChild != null; }
  54. }
  55. [MonoTODO]
  56. public virtual string InnerText {
  57. get {
  58. StringBuilder builder = new StringBuilder ();
  59. AppendChildValues (this, builder);
  60. return builder.ToString ();
  61. }
  62. set { throw new NotImplementedException (); }
  63. }
  64. private void AppendChildValues (XmlNode parent, StringBuilder builder)
  65. {
  66. XmlNode node = parent.FirstChild;
  67. while (node != null) {
  68. if (node.NodeType == XmlNodeType.Text)
  69. builder.Append (node.Value);
  70. AppendChildValues (node, builder);
  71. node = node.NextSibling;
  72. }
  73. }
  74. [MonoTODO("Setter.")]
  75. public virtual string InnerXml {
  76. get {
  77. StringWriter sw = new StringWriter ();
  78. XmlTextWriter xtw = new XmlTextWriter (sw);
  79. WriteContentTo(xtw);
  80. return sw.GetStringBuilder().ToString();
  81. }
  82. set { throw new NotImplementedException (); }
  83. }
  84. public virtual bool IsReadOnly {
  85. get { return false; }
  86. }
  87. [System.Runtime.CompilerServices.IndexerName("Item")]
  88. public virtual XmlElement this [string name] {
  89. get {
  90. foreach (XmlNode node in ChildNodes) {
  91. if ((node.NodeType == XmlNodeType.Element) &&
  92. (node.Name == name)) {
  93. return (XmlElement) node;
  94. }
  95. }
  96. return null;
  97. }
  98. }
  99. [System.Runtime.CompilerServices.IndexerName("Item")]
  100. public virtual XmlElement this [string localname, string ns] {
  101. get {
  102. foreach (XmlNode node in ChildNodes) {
  103. if ((node.NodeType == XmlNodeType.Element) &&
  104. (node.LocalName == localname) &&
  105. (node.NamespaceURI == ns)) {
  106. return (XmlElement) node;
  107. }
  108. }
  109. return null;
  110. }
  111. }
  112. public virtual XmlNode LastChild {
  113. get { return LastLinkedChild; }
  114. }
  115. internal virtual XmlLinkedNode LastLinkedChild {
  116. get { return null; }
  117. set { }
  118. }
  119. public abstract string LocalName { get; }
  120. public abstract string Name { get; }
  121. public virtual string NamespaceURI {
  122. get { return String.Empty; }
  123. }
  124. public virtual XmlNode NextSibling {
  125. get { return null; }
  126. }
  127. public abstract XmlNodeType NodeType { get; }
  128. internal virtual XPathNodeType XPathNodeType {
  129. get {
  130. return (XPathNodeType) (-1);
  131. }
  132. }
  133. public virtual string OuterXml {
  134. get {
  135. StringWriter sw = new StringWriter ();
  136. XmlTextWriter xtw = new XmlTextWriter (sw);
  137. WriteTo(xtw);
  138. return sw.GetStringBuilder().ToString();
  139. }
  140. }
  141. public virtual XmlDocument OwnerDocument {
  142. get { return ownerDocument; }
  143. }
  144. public virtual XmlNode ParentNode {
  145. get { return parentNode; }
  146. }
  147. public virtual string Prefix {
  148. get { return String.Empty; }
  149. set {}
  150. }
  151. public virtual XmlNode PreviousSibling {
  152. get { return null; }
  153. }
  154. public virtual string Value {
  155. get { return null; }
  156. set { throw new InvalidOperationException ("This node does not have a value"); }
  157. }
  158. #endregion
  159. #region Methods
  160. public virtual XmlNode AppendChild (XmlNode newChild)
  161. {
  162. // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
  163. return InsertBefore(newChild, null);
  164. // Below are formerly used logic.
  165. /* XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  166. if (NodeType == XmlNodeType.Document || NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || NodeType == XmlNodeType.DocumentFragment) {
  167. if (IsReadOnly)
  168. throw new ArgumentException ("The specified node is readonly.");
  169. if (newChild.OwnerDocument != ownerDoc)
  170. throw new ArgumentException ("Can't append a node created by another document.");
  171. // checking validity finished. then appending...
  172. ownerDoc.onNodeInserting (newChild, this);
  173. if(newChild.ParentNode != null)
  174. newChild.ParentNode.RemoveChild(newChild);
  175. if(newChild.NodeType == XmlNodeType.DocumentFragment)
  176. {
  177. int x = newChild.ChildNodes.Count;
  178. for(int i=0; i<x; i++)
  179. {
  180. // When this logic became to remove children in order, then index will have never to increments.
  181. XmlNode n = newChild.ChildNodes[0];
  182. this.AppendChild(n); // recursively invokes events. (It is compatible with MS implementation.)
  183. }
  184. }
  185. else
  186. {
  187. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  188. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  189. newLinkedChild.parentNode = this;
  190. if (lastLinkedChild != null)
  191. {
  192. newLinkedChild.NextLinkedSibling = lastLinkedChild.NextLinkedSibling;
  193. lastLinkedChild.NextLinkedSibling = newLinkedChild;
  194. }
  195. else
  196. newLinkedChild.NextLinkedSibling = newLinkedChild;
  197. LastLinkedChild = newLinkedChild;
  198. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  199. }
  200. return newChild;
  201. } else
  202. throw new InvalidOperationException();
  203. */ }
  204. public virtual XmlNode Clone ()
  205. {
  206. // By MS document, it is equivalent to CloneNode(true).
  207. return this.CloneNode(true);
  208. }
  209. public abstract XmlNode CloneNode (bool deep);
  210. [MonoTODO]
  211. public XPathNavigator CreateNavigator ()
  212. {
  213. return new XmlDocumentNavigator(this);
  214. }
  215. public IEnumerator GetEnumerator ()
  216. {
  217. return new XmlNodeListChildren(this).GetEnumerator();
  218. }
  219. // [MonoTODO]
  220. public virtual string GetNamespaceOfPrefix (string prefix)
  221. {
  222. XmlNamespaceManager nsmgr = ConstructNamespaceManager();
  223. return nsmgr.LookupNamespace(prefix);
  224. // throw new NotImplementedException ();
  225. }
  226. // [MonoTODO]
  227. public virtual string GetPrefixOfNamespace (string namespaceURI)
  228. {
  229. XmlNamespaceManager nsmgr = ConstructNamespaceManager();
  230. return nsmgr.LookupPrefix(namespaceURI);
  231. // throw new NotImplementedException ();
  232. }
  233. object ICloneable.Clone ()
  234. {
  235. return Clone ();
  236. }
  237. IEnumerator IEnumerable.GetEnumerator ()
  238. {
  239. return GetEnumerator ();
  240. }
  241. [MonoTODO]
  242. public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
  243. {
  244. // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
  245. // I took this way because rather than calling InsertAfter() from InsertBefore()
  246. // because current implementation of 'NextSibling' looks faster than 'PreviousSibling'.
  247. XmlNode argNode = (refChild == null) ? null : refChild.NextSibling;
  248. return InsertBefore(newChild, argNode);
  249. }
  250. [MonoTODO]
  251. public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
  252. {
  253. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  254. if (NodeType == XmlNodeType.Document || NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || NodeType == XmlNodeType.DocumentFragment)
  255. {
  256. if (IsReadOnly)
  257. throw new ArgumentException ("The specified node is readonly.");
  258. if (newChild.OwnerDocument != ownerDoc)
  259. throw new ArgumentException ("Can't append a node created by another document.");
  260. if(refChild != null)
  261. {
  262. if(newChild.OwnerDocument != refChild.OwnerDocument)
  263. throw new ArgumentException ("argument nodes are on the different documents.");
  264. if(refChild == ownerDoc.DocumentElement && (newChild is XmlElement || newChild is XmlCharacterData || newChild is XmlEntityReference))
  265. throw new XmlException("cannot insert this node to this position.");
  266. }
  267. // checking validity finished. then appending...
  268. ownerDoc.onNodeInserting (newChild, this);
  269. if(newChild.ParentNode != null)
  270. newChild.ParentNode.RemoveChild(newChild);
  271. if(newChild.NodeType == XmlNodeType.DocumentFragment)
  272. {
  273. int x = newChild.ChildNodes.Count;
  274. for(int i=0; i<x; i++)
  275. {
  276. // When this logic became to remove children in order, then index will have never to increments.
  277. XmlNode n = newChild.ChildNodes[0];
  278. this.InsertBefore(n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  279. }
  280. }
  281. else
  282. {
  283. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  284. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  285. newLinkedChild.parentNode = this;
  286. if(refChild == null)
  287. {
  288. // append last, so:
  289. // * set nextSibling of previous lastchild to newChild
  290. // * set lastchild = newChild
  291. // * set next of newChild to firstChild
  292. if(LastLinkedChild != null)
  293. {
  294. XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
  295. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  296. LastLinkedChild = newLinkedChild;
  297. newLinkedChild.NextLinkedSibling = formerFirst;
  298. }
  299. else
  300. {
  301. LastLinkedChild = newLinkedChild;
  302. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  303. }
  304. }
  305. else
  306. {
  307. // append not last, so:
  308. // * if newchild is first, then set next of lastchild is newChild.
  309. // otherwise, set next of previous sibling to newChild
  310. // * set next of newChild to refChild
  311. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  312. if(prev == null)
  313. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  314. else
  315. prev.NextLinkedSibling = newLinkedChild;
  316. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  317. }
  318. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  319. }
  320. return newChild;
  321. }
  322. else
  323. throw new InvalidOperationException();
  324. }
  325. [MonoTODO]
  326. public virtual void Normalize ()
  327. {
  328. throw new NotImplementedException ();
  329. }
  330. [MonoTODO]
  331. public virtual XmlNode PrependChild (XmlNode newChild)
  332. {
  333. throw new NotImplementedException ();
  334. }
  335. public virtual void RemoveAll ()
  336. {
  337. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  338. ownerDoc.onNodeRemoving (this, this.ParentNode);
  339. LastLinkedChild = null;
  340. ownerDoc.onNodeRemoved (this, this.ParentNode);
  341. }
  342. public virtual XmlNode RemoveChild (XmlNode oldChild)
  343. {
  344. if(oldChild.ParentNode != this)
  345. throw new XmlException("specified child is not child of this node.");
  346. OwnerDocument.onNodeRemoving (oldChild, oldChild.ParentNode);
  347. if (NodeType == XmlNodeType.Document || NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || NodeType == XmlNodeType.DocumentFragment)
  348. {
  349. if (IsReadOnly)
  350. throw new ArgumentException();
  351. if (Object.ReferenceEquals(LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals(LastLinkedChild, oldChild))
  352. LastLinkedChild = null;
  353. else {
  354. XmlLinkedNode oldLinkedChild = (XmlLinkedNode)oldChild;
  355. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  356. while (!Object.ReferenceEquals(beforeLinkedChild.NextLinkedSibling, LastLinkedChild) && !Object.ReferenceEquals(beforeLinkedChild.NextLinkedSibling, oldLinkedChild))
  357. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  358. if (!Object.ReferenceEquals(beforeLinkedChild.NextLinkedSibling, oldLinkedChild))
  359. throw new ArgumentException();
  360. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  361. oldLinkedChild.NextLinkedSibling = null;
  362. }
  363. OwnerDocument.onNodeRemoved (oldChild, oldChild.ParentNode);
  364. oldChild.parentNode = null; // clear parent 'after' above logic.
  365. return oldChild;
  366. }
  367. else
  368. throw new ArgumentException();
  369. }
  370. [MonoTODO]
  371. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  372. {
  373. throw new NotImplementedException ();
  374. }
  375. public XmlNodeList SelectNodes (string xpath)
  376. {
  377. return SelectNodes (xpath, null);
  378. }
  379. [MonoTODO]
  380. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  381. {
  382. XPathNavigator nav = CreateNavigator ();
  383. XPathExpression expr = nav.Compile (xpath);
  384. if (nsmgr != null)
  385. expr.SetContext (nsmgr);
  386. XPathNodeIterator iter = nav.Select (expr);
  387. ArrayList rgNodes = new ArrayList ();
  388. while (iter.MoveNext ())
  389. {
  390. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  391. }
  392. return new XmlNodeArrayList (rgNodes);
  393. }
  394. public XmlNode SelectSingleNode (string xpath)
  395. {
  396. return SelectSingleNode (xpath, null);
  397. }
  398. [MonoTODO]
  399. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  400. {
  401. XPathNavigator nav = CreateNavigator ();
  402. XPathExpression expr = nav.Compile (xpath);
  403. if (nsmgr != null)
  404. expr.SetContext (nsmgr);
  405. XPathNodeIterator iter = nav.Select (expr);
  406. if (!iter.MoveNext ())
  407. return null;
  408. return ((XmlDocumentNavigator) iter.Current).Node;
  409. }
  410. internal void SetParentNode (XmlNode parent)
  411. {
  412. parentNode = parent;
  413. }
  414. [MonoTODO]
  415. public virtual bool Supports (string feature, string version)
  416. {
  417. throw new NotImplementedException ();
  418. }
  419. public abstract void WriteContentTo (XmlWriter w);
  420. public abstract void WriteTo (XmlWriter w);
  421. // It parses with XmlReader and then construct DOM of the parsed contents.
  422. internal void ConstructDOM(XmlReader xmlReader, XmlNode currentNode)
  423. {
  424. // I am not confident whether this method should be placed in this class or not...
  425. // Please verify its validity and then erase this comment;-)
  426. XmlNode newNode;
  427. XmlDocument doc = currentNode is XmlDocument ? (XmlDocument)currentNode : currentNode.OwnerDocument;
  428. // Below are 'almost' copied from XmlDocument.Load(XmlReader xmlReader)
  429. while (xmlReader.Read ())
  430. {
  431. switch (xmlReader.NodeType)
  432. {
  433. case XmlNodeType.CDATA:
  434. newNode = doc.CreateCDataSection(xmlReader.Value);
  435. currentNode.AppendChild (newNode);
  436. break;
  437. case XmlNodeType.Comment:
  438. newNode = doc.CreateComment (xmlReader.Value);
  439. currentNode.AppendChild (newNode);
  440. break;
  441. case XmlNodeType.Element:
  442. XmlElement element = doc.CreateElement (xmlReader.Prefix, xmlReader.LocalName, xmlReader.NamespaceURI);
  443. currentNode.AppendChild (element);
  444. // set the element's attributes.
  445. while (xmlReader.MoveToNextAttribute ())
  446. {
  447. XmlAttribute attribute = doc.CreateAttribute (xmlReader.Prefix, xmlReader.LocalName, xmlReader.NamespaceURI);
  448. attribute.Value = xmlReader.Value;
  449. element.SetAttributeNode (attribute);
  450. }
  451. xmlReader.MoveToElement ();
  452. // if this element isn't empty, push it onto our "stack".
  453. if (!xmlReader.IsEmptyElement)
  454. currentNode = element;
  455. break;
  456. case XmlNodeType.EndElement:
  457. currentNode = currentNode.ParentNode;
  458. break;
  459. case XmlNodeType.ProcessingInstruction:
  460. newNode = doc.CreateProcessingInstruction (xmlReader.Name, xmlReader.Value);
  461. currentNode.AppendChild (newNode);
  462. break;
  463. case XmlNodeType.Text:
  464. newNode = doc.CreateTextNode (xmlReader.Value);
  465. currentNode.AppendChild (newNode);
  466. break;
  467. case XmlNodeType.XmlDeclaration:
  468. // empty strings are dummy, then gives over setting value contents to setter.
  469. newNode = doc.CreateXmlDeclaration("1.0" , String.Empty, String.Empty);
  470. ((XmlDeclaration)newNode).Value = xmlReader.Value;
  471. this.AppendChild(newNode);
  472. break;
  473. case XmlNodeType.DocumentType:
  474. XmlTextReader xmlTextReader = xmlReader as XmlTextReader;
  475. if(xmlTextReader != null)
  476. {
  477. XmlDocumentType dtdNode = doc.CreateDocumentType(xmlTextReader.Name, xmlTextReader.publicId, xmlTextReader.systemId, xmlTextReader.Value);
  478. this.AppendChild(dtdNode);
  479. }
  480. else
  481. throw new XmlException("construction of DocumentType node from this XmlReader is not supported.");
  482. break;
  483. case XmlNodeType.EntityReference:
  484. newNode = doc.CreateEntityReference(xmlReader.Name);
  485. currentNode.AppendChild(newNode);
  486. break;
  487. case XmlNodeType.SignificantWhitespace:
  488. newNode = doc.CreateSignificantWhitespace(xmlReader.Value);
  489. currentNode.AppendChild(newNode);
  490. break;
  491. case XmlNodeType.Whitespace:
  492. if(doc.PreserveWhitespace)
  493. {
  494. newNode = doc.CreateWhitespace(xmlReader.Value);
  495. currentNode.AppendChild(newNode);
  496. }
  497. break;
  498. }
  499. }
  500. }
  501. // It parses this and all the ancestor elements,
  502. // find 'xmlns' declarations, stores and then return them.
  503. // TODO: tests
  504. internal XmlNamespaceManager ConstructNamespaceManager()
  505. {
  506. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  507. XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
  508. XmlElement el = null;
  509. switch(this.NodeType)
  510. {
  511. case XmlNodeType.Attribute:
  512. el = ((XmlAttribute)this).OwnerElement;
  513. break;
  514. case XmlNodeType.Element:
  515. el = this as XmlElement;
  516. break;
  517. default:
  518. el = this.ParentNode as XmlElement;
  519. break;
  520. }
  521. while(el != null)
  522. {
  523. foreach(XmlAttribute attr in el.Attributes)
  524. {
  525. if(attr.Prefix == "xmlns" || (attr.Name == "xmlns" && attr.Prefix == String.Empty))
  526. {
  527. if(nsmgr.LookupNamespace(attr.LocalName) == null )
  528. {
  529. nsmgr.AddNamespace(attr.LocalName, attr.Value);
  530. }
  531. }
  532. }
  533. // When reached to document, then it will set null value :)
  534. el = el.ParentNode as XmlElement;
  535. }
  536. return nsmgr;
  537. }
  538. #endregion
  539. }
  540. }