XmlNode.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 || NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || NodeType == XmlNodeType.DocumentFragment) {
  253. if (IsReadOnly)
  254. throw new ArgumentException ("The specified node is readonly.");
  255. if (newChild.OwnerDocument != ownerDoc)
  256. throw new ArgumentException ("Can't append a node created by another document.");
  257. if(refChild != null) {
  258. if(newChild.OwnerDocument != refChild.OwnerDocument)
  259. throw new ArgumentException ("argument nodes are on the different documents.");
  260. }
  261. if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement || newChild is XmlCharacterData || newChild is XmlEntityReference))
  262. throw new XmlException ("cannot insert this node to this position.");
  263. // checking validity finished. then appending...
  264. ownerDoc.onNodeInserting (newChild, this);
  265. if(newChild.ParentNode != null)
  266. newChild.ParentNode.RemoveChild (newChild);
  267. if(newChild.NodeType == XmlNodeType.DocumentFragment) {
  268. int x = newChild.ChildNodes.Count;
  269. for(int i=0; i<x; i++) {
  270. XmlNode n = newChild.ChildNodes [0];
  271. this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  272. }
  273. }
  274. else {
  275. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  276. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  277. newLinkedChild.parentNode = this;
  278. if(refChild == null) {
  279. // append last, so:
  280. // * set nextSibling of previous lastchild to newChild
  281. // * set lastchild = newChild
  282. // * set next of newChild to firstChild
  283. if(LastLinkedChild != null) {
  284. XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
  285. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  286. LastLinkedChild = newLinkedChild;
  287. newLinkedChild.NextLinkedSibling = formerFirst;
  288. }
  289. else {
  290. LastLinkedChild = newLinkedChild;
  291. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  292. }
  293. }
  294. else {
  295. // append not last, so:
  296. // * if newchild is first, then set next of lastchild is newChild.
  297. // otherwise, set next of previous sibling to newChild
  298. // * set next of newChild to refChild
  299. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  300. if(prev == null)
  301. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  302. else
  303. prev.NextLinkedSibling = newLinkedChild;
  304. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  305. }
  306. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  307. }
  308. return newChild;
  309. }
  310. else
  311. throw new InvalidOperationException ();
  312. }
  313. [MonoTODO]
  314. public virtual void Normalize ()
  315. {
  316. throw new NotImplementedException ();
  317. }
  318. public virtual XmlNode PrependChild (XmlNode newChild)
  319. {
  320. return InsertAfter (newChild, null);
  321. }
  322. public virtual void RemoveAll ()
  323. {
  324. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  325. ownerDoc.onNodeRemoving (this, this.ParentNode);
  326. LastLinkedChild = null;
  327. ownerDoc.onNodeRemoved (this, this.ParentNode);
  328. }
  329. public virtual XmlNode RemoveChild (XmlNode oldChild)
  330. {
  331. if(oldChild.ParentNode != this)
  332. throw new XmlException ("specified child is not child of this node.");
  333. OwnerDocument.onNodeRemoving (oldChild, oldChild.ParentNode);
  334. if (NodeType == XmlNodeType.Document || NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Attribute || NodeType == XmlNodeType.DocumentFragment) {
  335. if (IsReadOnly)
  336. throw new ArgumentException ();
  337. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  338. LastLinkedChild = null;
  339. else {
  340. XmlLinkedNode oldLinkedChild = (XmlLinkedNode)oldChild;
  341. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  342. while (!Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) && !Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild))
  343. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  344. if (!Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild))
  345. throw new ArgumentException ();
  346. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  347. oldLinkedChild.NextLinkedSibling = null;
  348. }
  349. OwnerDocument.onNodeRemoved (oldChild, oldChild.ParentNode);
  350. oldChild.parentNode = null; // clear parent 'after' above logic.
  351. return oldChild;
  352. }
  353. else
  354. throw new ArgumentException ();
  355. }
  356. [MonoTODO]
  357. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  358. {
  359. throw new NotImplementedException ();
  360. }
  361. public XmlNodeList SelectNodes (string xpath)
  362. {
  363. return SelectNodes (xpath, null);
  364. }
  365. [MonoTODO]
  366. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  367. {
  368. XPathNavigator nav = CreateNavigator ();
  369. XPathExpression expr = nav.Compile (xpath);
  370. if (nsmgr != null)
  371. expr.SetContext (nsmgr);
  372. XPathNodeIterator iter = nav.Select (expr);
  373. ArrayList rgNodes = new ArrayList ();
  374. while (iter.MoveNext ())
  375. {
  376. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  377. }
  378. return new XmlNodeArrayList (rgNodes);
  379. }
  380. public XmlNode SelectSingleNode (string xpath)
  381. {
  382. return SelectSingleNode (xpath, null);
  383. }
  384. [MonoTODO]
  385. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  386. {
  387. XPathNavigator nav = CreateNavigator ();
  388. XPathExpression expr = nav.Compile (xpath);
  389. if (nsmgr != null)
  390. expr.SetContext (nsmgr);
  391. XPathNodeIterator iter = nav.Select (expr);
  392. if (!iter.MoveNext ())
  393. return null;
  394. return ((XmlDocumentNavigator) iter.Current).Node;
  395. }
  396. internal void SetParentNode (XmlNode parent)
  397. {
  398. parentNode = parent;
  399. }
  400. [MonoTODO]
  401. public virtual bool Supports (string feature, string version)
  402. {
  403. throw new NotImplementedException ();
  404. }
  405. public abstract void WriteContentTo (XmlWriter w);
  406. public abstract void WriteTo (XmlWriter w);
  407. // It parses with XmlReader and then construct DOM of the parsed contents.
  408. internal void ConstructDOM (XmlReader xmlReader, XmlNode currentNode)
  409. {
  410. // I am not confident whether this method should be placed in this class or not...
  411. // Please verify its validity and then erase this comment;-)
  412. XmlNode newNode;
  413. XmlDocument doc = currentNode is XmlDocument ? (XmlDocument)currentNode : currentNode.OwnerDocument;
  414. // Below are 'almost' copied from XmlDocument.Load(XmlReader xmlReader)
  415. while (xmlReader.Read ()) {
  416. switch (xmlReader.NodeType) {
  417. case XmlNodeType.CDATA:
  418. newNode = doc.CreateCDataSection (xmlReader.Value);
  419. currentNode.AppendChild (newNode);
  420. break;
  421. case XmlNodeType.Comment:
  422. newNode = doc.CreateComment (xmlReader.Value);
  423. currentNode.AppendChild (newNode);
  424. break;
  425. case XmlNodeType.Element:
  426. XmlElement element = doc.CreateElement (xmlReader.Prefix, xmlReader.LocalName, xmlReader.NamespaceURI);
  427. element.IsEmpty = xmlReader.IsEmptyElement;
  428. currentNode.AppendChild (element);
  429. // set the element's attributes.
  430. while (xmlReader.MoveToNextAttribute ()) {
  431. XmlAttribute attribute = doc.CreateAttribute (xmlReader.Prefix, xmlReader.LocalName, xmlReader.NamespaceURI);
  432. attribute.Value = xmlReader.Value;
  433. element.SetAttributeNode (attribute);
  434. }
  435. xmlReader.MoveToElement ();
  436. // if this element isn't empty, push it onto our "stack".
  437. if (!xmlReader.IsEmptyElement)
  438. currentNode = element;
  439. break;
  440. case XmlNodeType.EndElement:
  441. currentNode = currentNode.ParentNode;
  442. break;
  443. case XmlNodeType.ProcessingInstruction:
  444. newNode = doc.CreateProcessingInstruction (xmlReader.Name, xmlReader.Value);
  445. currentNode.AppendChild (newNode);
  446. break;
  447. case XmlNodeType.Text:
  448. newNode = doc.CreateTextNode (xmlReader.Value);
  449. currentNode.AppendChild (newNode);
  450. break;
  451. case XmlNodeType.XmlDeclaration:
  452. // empty strings are dummy, then gives over setting value contents to setter.
  453. newNode = doc.CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
  454. ((XmlDeclaration)newNode).Value = xmlReader.Value;
  455. this.AppendChild (newNode);
  456. break;
  457. case XmlNodeType.DocumentType:
  458. XmlTextReader xmlTextReader = xmlReader as XmlTextReader;
  459. if(xmlTextReader != null) {
  460. XmlDocumentType dtdNode = doc.CreateDocumentType (xmlTextReader.Name, xmlTextReader.publicId, xmlTextReader.systemId, xmlTextReader.Value);
  461. this.AppendChild (dtdNode);
  462. }
  463. else
  464. throw new XmlException ("construction of DocumentType node from this XmlReader is not supported.");
  465. break;
  466. case XmlNodeType.EntityReference:
  467. newNode = doc.CreateEntityReference (xmlReader.Name);
  468. currentNode.AppendChild (newNode);
  469. break;
  470. case XmlNodeType.SignificantWhitespace:
  471. newNode = doc.CreateSignificantWhitespace (xmlReader.Value);
  472. currentNode.AppendChild (newNode);
  473. break;
  474. case XmlNodeType.Whitespace:
  475. if(doc.PreserveWhitespace) {
  476. newNode = doc.CreateWhitespace (xmlReader.Value);
  477. currentNode.AppendChild (newNode);
  478. }
  479. break;
  480. }
  481. }
  482. }
  483. // It parses this and all the ancestor elements,
  484. // find 'xmlns' declarations, stores and then return them.
  485. // TODO: tests
  486. internal XmlNamespaceManager ConstructNamespaceManager ()
  487. {
  488. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  489. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  490. XmlElement el = null;
  491. switch(this.NodeType) {
  492. case XmlNodeType.Attribute:
  493. el = ((XmlAttribute)this).OwnerElement;
  494. break;
  495. case XmlNodeType.Element:
  496. el = this as XmlElement;
  497. break;
  498. default:
  499. el = this.ParentNode as XmlElement;
  500. break;
  501. }
  502. while(el != null) {
  503. foreach(XmlAttribute attr in el.Attributes) {
  504. if(attr.Prefix == "xmlns" || (attr.Name == "xmlns" && attr.Prefix == String.Empty)) {
  505. if(nsmgr.LookupNamespace (attr.LocalName) == null )
  506. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  507. }
  508. }
  509. // When reached to document, then it will set null value :)
  510. el = el.ParentNode as XmlElement;
  511. }
  512. return nsmgr;
  513. }
  514. #endregion
  515. }
  516. }