XmlNode.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections;
  33. using System.Globalization;
  34. using System.IO;
  35. using System.Text;
  36. using System.Xml.XPath;
  37. namespace System.Xml
  38. {
  39. public abstract class XmlNode : ICloneable, IEnumerable, IXPathNavigable
  40. {
  41. #region Fields
  42. XmlDocument ownerDocument;
  43. XmlNode parentNode;
  44. XmlLinkedNode lastLinkedChild;
  45. XmlNodeListChildren childNodes;
  46. bool isReadOnly;
  47. #endregion
  48. #region Constructors
  49. internal XmlNode (XmlDocument ownerDocument)
  50. {
  51. this.ownerDocument = ownerDocument;
  52. }
  53. #endregion
  54. #region Properties
  55. public virtual XmlAttributeCollection Attributes {
  56. get { return null; }
  57. }
  58. public virtual string BaseURI {
  59. get {
  60. // Isn't it conformant to W3C XML Base Recommendation?
  61. // As far as I tested, there are not...
  62. return (ParentNode != null) ? ParentNode.BaseURI : String.Empty;
  63. }
  64. }
  65. public virtual XmlNodeList ChildNodes {
  66. get {
  67. if (childNodes == null)
  68. childNodes = new XmlNodeListChildren (this);
  69. return childNodes;
  70. }
  71. }
  72. public virtual XmlNode FirstChild {
  73. get {
  74. if (LastChild != null) {
  75. return LastLinkedChild.NextLinkedSibling;
  76. }
  77. else {
  78. return null;
  79. }
  80. }
  81. }
  82. public virtual bool HasChildNodes {
  83. get { return LastChild != null; }
  84. }
  85. public virtual string InnerText {
  86. get {
  87. StringBuilder builder = new StringBuilder ();
  88. AppendChildValues (this, builder);
  89. return builder.ToString ();
  90. }
  91. set { throw new InvalidOperationException ("This node is read only. Cannot be modified."); }
  92. }
  93. private void AppendChildValues (XmlNode parent, StringBuilder builder)
  94. {
  95. XmlNode node = parent.FirstChild;
  96. while (node != null) {
  97. switch (node.NodeType) {
  98. case XmlNodeType.Text:
  99. case XmlNodeType.CDATA:
  100. case XmlNodeType.SignificantWhitespace:
  101. case XmlNodeType.Whitespace:
  102. builder.Append (node.Value);
  103. break;
  104. }
  105. AppendChildValues (node, builder);
  106. node = node.NextSibling;
  107. }
  108. }
  109. public virtual string InnerXml {
  110. get {
  111. StringWriter sw = new StringWriter ();
  112. XmlTextWriter xtw = new XmlTextWriter (sw);
  113. WriteContentTo (xtw);
  114. return sw.GetStringBuilder ().ToString ();
  115. }
  116. set {
  117. throw new InvalidOperationException ("This node is readonly or doesn't have any children.");
  118. }
  119. }
  120. public virtual bool IsReadOnly {
  121. get { return isReadOnly; }
  122. }
  123. [System.Runtime.CompilerServices.IndexerName("Item")]
  124. public virtual XmlElement this [string name] {
  125. get {
  126. for (int i = 0; i < ChildNodes.Count; i++) {
  127. XmlNode node = ChildNodes [i];
  128. if ((node.NodeType == XmlNodeType.Element) &&
  129. (node.Name == name)) {
  130. return (XmlElement) node;
  131. }
  132. }
  133. return null;
  134. }
  135. }
  136. [System.Runtime.CompilerServices.IndexerName("Item")]
  137. public virtual XmlElement this [string localname, string ns] {
  138. get {
  139. for (int i = 0; i < ChildNodes.Count; i++) {
  140. XmlNode node = ChildNodes [i];
  141. if ((node.NodeType == XmlNodeType.Element) &&
  142. (node.LocalName == localname) &&
  143. (node.NamespaceURI == ns)) {
  144. return (XmlElement) node;
  145. }
  146. }
  147. return null;
  148. }
  149. }
  150. public virtual XmlNode LastChild {
  151. get { return LastLinkedChild; }
  152. }
  153. internal virtual XmlLinkedNode LastLinkedChild {
  154. get { return lastLinkedChild; }
  155. set { lastLinkedChild = value; }
  156. }
  157. public abstract string LocalName { get; }
  158. public abstract string Name { get; }
  159. public virtual string NamespaceURI {
  160. get { return String.Empty; }
  161. }
  162. public virtual XmlNode NextSibling {
  163. get { return null; }
  164. }
  165. public abstract XmlNodeType NodeType { get; }
  166. internal virtual XPathNodeType XPathNodeType {
  167. get {
  168. throw new InvalidOperationException ("Can not get XPath node type from " + this.GetType ().ToString ());
  169. }
  170. }
  171. public virtual string OuterXml {
  172. get {
  173. StringWriter sw = new StringWriter ();
  174. XmlTextWriter xtw = new XmlTextWriter (sw);
  175. WriteTo (xtw);
  176. return sw.ToString ();
  177. }
  178. }
  179. public virtual XmlDocument OwnerDocument {
  180. get { return ownerDocument; }
  181. }
  182. public virtual XmlNode ParentNode {
  183. get { return parentNode; }
  184. }
  185. public virtual string Prefix {
  186. get { return String.Empty; }
  187. set {}
  188. }
  189. public virtual XmlNode PreviousSibling {
  190. get { return null; }
  191. }
  192. public virtual string Value {
  193. get { return null; }
  194. set { throw new InvalidOperationException ("This node does not have a value"); }
  195. }
  196. internal virtual string XmlLang {
  197. get {
  198. if(Attributes != null)
  199. for (int i = 0; i < Attributes.Count; i++) {
  200. XmlAttribute attr = Attributes [i];
  201. if(attr.Name == "xml:lang")
  202. return attr.Value;
  203. }
  204. return (ParentNode != null) ? ParentNode.XmlLang : OwnerDocument.XmlLang;
  205. }
  206. }
  207. internal virtual XmlSpace XmlSpace {
  208. get {
  209. if(Attributes != null) {
  210. for (int i = 0; i < Attributes.Count; i++) {
  211. XmlAttribute attr = Attributes [i];
  212. if(attr.Name == "xml:space") {
  213. switch(attr.Value) {
  214. case "preserve": return XmlSpace.Preserve;
  215. case "default": return XmlSpace.Default;
  216. }
  217. break;
  218. }
  219. }
  220. }
  221. return (ParentNode != null) ? ParentNode.XmlSpace : OwnerDocument.XmlSpace;
  222. }
  223. }
  224. #endregion
  225. #region Methods
  226. public virtual XmlNode AppendChild (XmlNode newChild)
  227. {
  228. // I assume that AppendChild(n) equals to InsertAfter(n, this.LastChild) or InsertBefore(n, null)
  229. return InsertBefore (newChild, null);
  230. }
  231. public virtual XmlNode Clone ()
  232. {
  233. // By MS document, it is equivalent to CloneNode(true).
  234. return this.CloneNode (true);
  235. }
  236. public abstract XmlNode CloneNode (bool deep);
  237. public XPathNavigator CreateNavigator ()
  238. {
  239. XmlDocument document = this.NodeType == XmlNodeType.Document ?
  240. this as XmlDocument : this.ownerDocument;
  241. return document.CreateNavigator (this);
  242. }
  243. public IEnumerator GetEnumerator ()
  244. {
  245. return ChildNodes.GetEnumerator ();
  246. }
  247. public virtual string GetNamespaceOfPrefix (string prefix)
  248. {
  249. if (prefix == null)
  250. throw new ArgumentNullException ("prefix");
  251. XmlNode node;
  252. switch (NodeType) {
  253. case XmlNodeType.Attribute:
  254. node = ((XmlAttribute) this).OwnerElement;
  255. if (node == null)
  256. return String.Empty;
  257. break;
  258. case XmlNodeType.Element:
  259. node = this;
  260. break;
  261. default:
  262. node = ParentNode;
  263. break;
  264. }
  265. while (node != null) {
  266. if (node.Prefix == prefix)
  267. return node.NamespaceURI;
  268. if (node.Attributes != null) {
  269. int count = node.Attributes.Count;
  270. for (int i = 0; i < count; i++) {
  271. XmlAttribute attr = node.Attributes [i];
  272. if (prefix == attr.LocalName && attr.Prefix == "xmlns"
  273. || attr.Name == "xmlns" && prefix == String.Empty)
  274. return attr.Value;
  275. }
  276. }
  277. node = node.ParentNode;
  278. }
  279. return String.Empty;
  280. }
  281. public virtual string GetPrefixOfNamespace (string namespaceURI)
  282. {
  283. XmlNode node;
  284. switch (NodeType) {
  285. case XmlNodeType.Attribute:
  286. node = ((XmlAttribute) this).OwnerElement;
  287. break;
  288. case XmlNodeType.Element:
  289. node = this;
  290. break;
  291. default:
  292. node = ParentNode;
  293. break;
  294. }
  295. while (node != null && node.Attributes != null) {
  296. for (int i = 0; i < Attributes.Count; i++) {
  297. XmlAttribute attr = Attributes [i];
  298. if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
  299. return attr.LocalName;
  300. else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
  301. return String.Empty;
  302. }
  303. node = node.ParentNode;
  304. }
  305. return String.Empty;
  306. }
  307. object ICloneable.Clone ()
  308. {
  309. return Clone ();
  310. }
  311. IEnumerator IEnumerable.GetEnumerator ()
  312. {
  313. return GetEnumerator ();
  314. }
  315. public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
  316. {
  317. // InsertAfter(n1, n2) is equivalent to InsertBefore(n1, n2.PreviousSibling).
  318. // I took this way because current implementation
  319. // Calling InsertBefore() in this method is faster than
  320. // the counterpart, since NextSibling is faster than
  321. // PreviousSibling (these children are forward-only list).
  322. XmlNode argNode = null;
  323. if (refChild != null)
  324. argNode = refChild.NextSibling;
  325. else if (ChildNodes.Count > 0)
  326. argNode = FirstChild;
  327. return InsertBefore (newChild, argNode);
  328. }
  329. public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
  330. {
  331. return InsertBefore (newChild, refChild, true, true);
  332. }
  333. // check for the node to be one of node ancestors
  334. internal bool IsAncestor (XmlNode newChild)
  335. {
  336. XmlNode currNode = this.ParentNode;
  337. while(currNode != null)
  338. {
  339. if(currNode == newChild)
  340. return true;
  341. currNode = currNode.ParentNode;
  342. }
  343. return false;
  344. }
  345. internal XmlNode InsertBefore (XmlNode newChild, XmlNode refChild, bool checkNodeType, bool raiseEvent)
  346. {
  347. if (checkNodeType)
  348. CheckNodeInsertion (newChild, refChild);
  349. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
  350. if (raiseEvent)
  351. ownerDoc.onNodeInserting (newChild, this);
  352. if (newChild.ParentNode != null)
  353. newChild.ParentNode.RemoveChild (newChild, checkNodeType);
  354. if (newChild.NodeType == XmlNodeType.DocumentFragment) {
  355. int x = newChild.ChildNodes.Count;
  356. for (int i = 0; i < x; i++) {
  357. XmlNode n = newChild.ChildNodes [0];
  358. this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  359. }
  360. }
  361. else {
  362. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  363. newLinkedChild.parentNode = this;
  364. if (refChild == null) {
  365. // newChild is the last child:
  366. // * set newChild as NextSibling of the existing lastchild
  367. // * set LastChild = newChild
  368. // * set NextSibling of newChild as FirstChild
  369. if (LastLinkedChild != null) {
  370. XmlLinkedNode formerFirst = (XmlLinkedNode) FirstChild;
  371. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  372. LastLinkedChild = newLinkedChild;
  373. newLinkedChild.NextLinkedSibling = formerFirst;
  374. } else {
  375. LastLinkedChild = newLinkedChild;
  376. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  377. }
  378. } else {
  379. // newChild is not the last child:
  380. // * if newchild is first, then set next of lastchild is newChild.
  381. // otherwise, set next of previous sibling to newChild
  382. // * set next of newChild to refChild
  383. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  384. if (prev == null)
  385. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  386. else
  387. prev.NextLinkedSibling = newLinkedChild;
  388. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  389. }
  390. switch (newChild.NodeType) {
  391. case XmlNodeType.EntityReference:
  392. ((XmlEntityReference) newChild).SetReferencedEntityContent ();
  393. break;
  394. case XmlNodeType.Entity:
  395. ((XmlEntity) newChild).SetEntityContent ();
  396. break;
  397. case XmlNodeType.DocumentType:
  398. foreach (XmlEntity ent in ((XmlDocumentType)newChild).Entities)
  399. ent.SetEntityContent ();
  400. break;
  401. }
  402. if (raiseEvent)
  403. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  404. }
  405. return newChild;
  406. }
  407. private void CheckNodeInsertion (XmlNode newChild, XmlNode refChild)
  408. {
  409. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument) this : OwnerDocument;
  410. if (NodeType != XmlNodeType.Element &&
  411. NodeType != XmlNodeType.Attribute &&
  412. NodeType != XmlNodeType.Document &&
  413. NodeType != XmlNodeType.DocumentFragment)
  414. throw new InvalidOperationException (String.Format ("Node cannot be appended to current node {0}.", NodeType));
  415. switch (NodeType) {
  416. case XmlNodeType.Attribute:
  417. switch (newChild.NodeType) {
  418. case XmlNodeType.Text:
  419. case XmlNodeType.EntityReference:
  420. break;
  421. default:
  422. throw new InvalidOperationException (String.Format (
  423. "Cannot insert specified type of node {0} as a child of this node {1}.",
  424. newChild.NodeType, NodeType));
  425. }
  426. break;
  427. case XmlNodeType.Element:
  428. switch (newChild.NodeType) {
  429. case XmlNodeType.Attribute:
  430. case XmlNodeType.Document:
  431. case XmlNodeType.DocumentType:
  432. case XmlNodeType.Entity:
  433. case XmlNodeType.Notation:
  434. case XmlNodeType.XmlDeclaration:
  435. throw new InvalidOperationException ("Cannot insert specified type of node as a child of this node.");
  436. }
  437. break;
  438. }
  439. if (IsReadOnly)
  440. throw new InvalidOperationException ("The node is readonly.");
  441. if (newChild.OwnerDocument != ownerDoc)
  442. throw new ArgumentException ("Can't append a node created by another document.");
  443. if (refChild != null) {
  444. if (refChild.ParentNode != this)
  445. throw new ArgumentException ("The reference node is not a child of this node.");
  446. }
  447. if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement) && newChild != ownerDoc.DocumentElement)
  448. throw new XmlException ("multiple document element not allowed.");
  449. // checking validity finished. then appending...
  450. if (newChild == this || IsAncestor (newChild))
  451. throw new ArgumentException("Cannot insert a node or any ancestor of that node as a child of itself.");
  452. }
  453. public virtual void Normalize ()
  454. {
  455. StringBuilder tmpBuilder = new StringBuilder ();
  456. int count = this.ChildNodes.Count;
  457. int start = 0;
  458. for (int i = 0; i < count; i++) {
  459. XmlNode c = ChildNodes [i];
  460. switch (c.NodeType) {
  461. case XmlNodeType.Text:
  462. case XmlNodeType.Whitespace:
  463. case XmlNodeType.SignificantWhitespace:
  464. tmpBuilder.Append (c.Value);
  465. break;
  466. default:
  467. c.Normalize ();
  468. NormalizeRange (start, i, tmpBuilder);
  469. // Continue to normalize from next node.
  470. start = i + 1;
  471. break;
  472. }
  473. }
  474. if (start < count) {
  475. NormalizeRange (start, count, tmpBuilder);
  476. }
  477. }
  478. private void NormalizeRange (int start, int i, StringBuilder tmpBuilder)
  479. {
  480. int keepPos = -1;
  481. // If Texts and Whitespaces are mixed, Text takes precedence to remain.
  482. // i.e. Whitespace should be removed.
  483. for (int j = start; j < i; j++) {
  484. XmlNode keep = ChildNodes [j];
  485. if (keep.NodeType == XmlNodeType.Text) {
  486. keepPos = j;
  487. break;
  488. }
  489. else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
  490. keepPos = j;
  491. // but don't break up to find Text nodes.
  492. }
  493. if (keepPos >= 0) {
  494. for (int del = start; del < keepPos; del++)
  495. RemoveChild (ChildNodes [start]);
  496. int rest = i - keepPos - 1;
  497. for (int del = 0; del < rest; del++) {
  498. RemoveChild (ChildNodes [start + 1]);
  499. }
  500. }
  501. if (keepPos >= 0)
  502. ChildNodes [start].Value = tmpBuilder.ToString ();
  503. // otherwise nothing to be normalized
  504. tmpBuilder.Length = 0;
  505. }
  506. public virtual XmlNode PrependChild (XmlNode newChild)
  507. {
  508. return InsertAfter (newChild, null);
  509. }
  510. public virtual void RemoveAll ()
  511. {
  512. if (Attributes != null)
  513. Attributes.RemoveAll ();
  514. XmlNode next = null;
  515. for (XmlNode node = FirstChild; node != null; node = next) {
  516. next = node.NextSibling;
  517. RemoveChild (node);
  518. }
  519. }
  520. public virtual XmlNode RemoveChild (XmlNode oldChild)
  521. {
  522. return RemoveChild (oldChild, true);
  523. }
  524. private void CheckNodeRemoval ()
  525. {
  526. if (NodeType != XmlNodeType.Attribute &&
  527. NodeType != XmlNodeType.Element &&
  528. NodeType != XmlNodeType.Document &&
  529. NodeType != XmlNodeType.DocumentFragment)
  530. throw new ArgumentException (String.Format ("This {0} node cannot remove its child.", NodeType));
  531. if (IsReadOnly)
  532. throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
  533. }
  534. internal XmlNode RemoveChild (XmlNode oldChild, bool checkNodeType)
  535. {
  536. if (oldChild == null)
  537. throw new NullReferenceException ();
  538. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  539. if(oldChild.ParentNode != this)
  540. throw new ArgumentException ("The node to be removed is not a child of this node.");
  541. if (checkNodeType)
  542. ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
  543. if (checkNodeType)
  544. CheckNodeRemoval ();
  545. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  546. // If there is only one children, simply clear.
  547. LastLinkedChild = null;
  548. else {
  549. XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
  550. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  551. XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
  552. while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
  553. Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  554. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  555. if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  556. throw new ArgumentException ();
  557. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  558. // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
  559. if (oldLinkedChild.NextLinkedSibling == firstChild)
  560. this.LastLinkedChild = beforeLinkedChild;
  561. oldLinkedChild.NextLinkedSibling = null;
  562. }
  563. if (checkNodeType)
  564. ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
  565. oldChild.parentNode = null; // clear parent 'after' above logic.
  566. return oldChild;
  567. }
  568. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  569. {
  570. if(oldChild.ParentNode != this)
  571. throw new ArgumentException ("The node to be removed is not a child of this node.");
  572. if (newChild == this || IsAncestor (newChild))
  573. throw new InvalidOperationException("Cannot insert a node or any ancestor of that node as a child of itself.");
  574. for (int i = 0; i < ChildNodes.Count; i++) {
  575. XmlNode n = ChildNodes [i];
  576. if(n == oldChild) {
  577. XmlNode prev = oldChild.PreviousSibling;
  578. RemoveChild (oldChild);
  579. InsertAfter (newChild, prev);
  580. break;
  581. }
  582. }
  583. return oldChild;
  584. }
  585. internal void SearchDescendantElements (string name, bool matchAll, ArrayList list)
  586. {
  587. for (int i = 0; i < ChildNodes.Count; i++) {
  588. XmlNode n = ChildNodes [i];
  589. if (n.NodeType != XmlNodeType.Element)
  590. continue;
  591. if (matchAll || n.Name == name)
  592. list.Add (n);
  593. n.SearchDescendantElements (name, matchAll, list);
  594. }
  595. }
  596. internal void SearchDescendantElements (string name, bool matchAllName, string ns, bool matchAllNS, ArrayList list)
  597. {
  598. for (int i = 0; i < ChildNodes.Count; i++) {
  599. XmlNode n = ChildNodes [i];
  600. if (n.NodeType != XmlNodeType.Element)
  601. continue;
  602. if ((matchAllName || n.LocalName == name)
  603. && (matchAllNS || n.NamespaceURI == ns))
  604. list.Add (n);
  605. n.SearchDescendantElements (name, matchAllName, ns, matchAllNS, list);
  606. }
  607. }
  608. public XmlNodeList SelectNodes (string xpath)
  609. {
  610. return SelectNodes (xpath, null);
  611. }
  612. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  613. {
  614. XPathNavigator nav = CreateNavigator ();
  615. XPathExpression expr = nav.Compile (xpath);
  616. if (nsmgr != null)
  617. expr.SetContext (nsmgr);
  618. XPathNodeIterator iter = nav.Select (expr);
  619. ArrayList rgNodes = new ArrayList ();
  620. while (iter.MoveNext ())
  621. {
  622. rgNodes.Add (((IHasXmlNode) iter.Current).GetNode ());
  623. }
  624. return new XmlNodeArrayList (rgNodes);
  625. }
  626. public XmlNode SelectSingleNode (string xpath)
  627. {
  628. return SelectSingleNode (xpath, null);
  629. }
  630. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  631. {
  632. XPathNavigator nav = CreateNavigator ();
  633. XPathExpression expr = nav.Compile (xpath);
  634. if (nsmgr != null)
  635. expr.SetContext (nsmgr);
  636. XPathNodeIterator iter = nav.Select (expr);
  637. if (!iter.MoveNext ())
  638. return null;
  639. return ((IHasXmlNode) iter.Current).GetNode ();
  640. }
  641. internal static void SetReadOnly (XmlNode n)
  642. {
  643. if (n.Attributes != null)
  644. for (int i = 0; i < n.Attributes.Count; i++)
  645. SetReadOnly (n.Attributes [i]);
  646. for (int i = 0; i < n.ChildNodes.Count; i++)
  647. SetReadOnly (n.ChildNodes [i]);
  648. n.isReadOnly = true;
  649. }
  650. internal void SetReadOnly ()
  651. {
  652. isReadOnly = true;
  653. }
  654. public virtual bool Supports (string feature, string version)
  655. {
  656. if (String.Compare (feature, "xml", true, CultureInfo.InvariantCulture) == 0 // not case-sensitive
  657. && (String.Compare (version, "1.0", true, CultureInfo.InvariantCulture) == 0
  658. || String.Compare (version, "2.0", true, CultureInfo.InvariantCulture) == 0))
  659. return true;
  660. else
  661. return false;
  662. }
  663. public abstract void WriteContentTo (XmlWriter w);
  664. public abstract void WriteTo (XmlWriter w);
  665. // It parses this and all the ancestor elements,
  666. // find 'xmlns' declarations, stores and then return them.
  667. internal XmlNamespaceManager ConstructNamespaceManager ()
  668. {
  669. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  670. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  671. XmlElement el = null;
  672. switch(this.NodeType) {
  673. case XmlNodeType.Attribute:
  674. el = ((XmlAttribute)this).OwnerElement;
  675. break;
  676. case XmlNodeType.Element:
  677. el = this as XmlElement;
  678. break;
  679. default:
  680. el = this.ParentNode as XmlElement;
  681. break;
  682. }
  683. while (el != null) {
  684. for (int i = 0; i < el.Attributes.Count; i++) {
  685. XmlAttribute attr = el.Attributes [i];
  686. if(attr.Prefix == "xmlns") {
  687. if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
  688. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  689. } else if(attr.Name == "xmlns") {
  690. if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
  691. nsmgr.AddNamespace (String.Empty, attr.Value);
  692. }
  693. }
  694. // When reached to document, then it will set null value :)
  695. el = el.ParentNode as XmlElement;
  696. }
  697. return nsmgr;
  698. }
  699. #endregion
  700. }
  701. }