XmlNode.cs 17 KB

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