2
0

XmlNode.cs 18 KB

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