XmlNode.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. StringBuilder tmpBuilder;
  24. #endregion
  25. #region Constructors
  26. internal XmlNode (XmlDocument ownerDocument)
  27. {
  28. this.ownerDocument = ownerDocument;
  29. }
  30. #endregion
  31. #region Properties
  32. public virtual XmlAttributeCollection Attributes {
  33. get { return null; }
  34. }
  35. public virtual string BaseURI {
  36. get {
  37. // Isn't it conformant to W3C XML Base Recommendation?
  38. // As far as I tested, there are not...
  39. return (ParentNode != null) ? ParentNode.BaseURI : OwnerDocument.BaseURI;
  40. }
  41. }
  42. public virtual XmlNodeList ChildNodes {
  43. get {
  44. return new XmlNodeListChildren (this);
  45. }
  46. }
  47. public virtual XmlNode FirstChild {
  48. get {
  49. if (LastChild != null) {
  50. return LastLinkedChild.NextLinkedSibling;
  51. }
  52. else {
  53. return null;
  54. }
  55. }
  56. }
  57. public virtual bool HasChildNodes {
  58. get { return LastChild != null; }
  59. }
  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 InvalidOperationException ("This node is read only. Cannot be modified."); }
  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 ("Can not get XPath node type from " + this.GetType ().ToString ());
  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. public XPathNavigator CreateNavigator ()
  208. {
  209. XmlDocument document = this.NodeType == XmlNodeType.Document ?
  210. this as XmlDocument : this.ownerDocument;
  211. return document.CreateNavigator (this);
  212. }
  213. public IEnumerator GetEnumerator ()
  214. {
  215. return new XmlNodeListChildren (this).GetEnumerator ();
  216. }
  217. public virtual string GetNamespaceOfPrefix (string prefix)
  218. {
  219. XmlNode node;
  220. switch (NodeType) {
  221. case XmlNodeType.Attribute:
  222. node = ((XmlAttribute) this).OwnerElement;
  223. break;
  224. case XmlNodeType.Element:
  225. node = this;
  226. break;
  227. default:
  228. node = ParentNode;
  229. break;
  230. }
  231. while (node.NodeType != XmlNodeType.Document) {
  232. foreach (XmlAttribute attr in node.Attributes) {
  233. if (prefix == attr.LocalName && attr.Prefix == "xmlns"
  234. || attr.Name == "xmlns" && prefix == String.Empty)
  235. return attr.Value;
  236. }
  237. node = node.ParentNode;
  238. }
  239. return null;
  240. }
  241. public virtual string GetPrefixOfNamespace (string namespaceURI)
  242. {
  243. XmlNode node;
  244. switch (NodeType) {
  245. case XmlNodeType.Attribute:
  246. node = ((XmlAttribute) this).OwnerElement;
  247. break;
  248. case XmlNodeType.Element:
  249. node = this;
  250. break;
  251. default:
  252. node = ParentNode;
  253. break;
  254. }
  255. while (node.NodeType != XmlNodeType.Document) {
  256. foreach (XmlAttribute attr in node.Attributes) {
  257. if (attr.Prefix == "xmlns" && attr.Value == namespaceURI)
  258. return attr.LocalName;
  259. else if (attr.Name == "xmlns" && attr.Value == namespaceURI)
  260. return String.Empty;
  261. }
  262. node = node.ParentNode;
  263. }
  264. return String.Empty;
  265. }
  266. object ICloneable.Clone ()
  267. {
  268. return Clone ();
  269. }
  270. IEnumerator IEnumerable.GetEnumerator ()
  271. {
  272. return GetEnumerator ();
  273. }
  274. public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
  275. {
  276. // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
  277. // I took this way because current implementation
  278. // Calling InsertAfter() from InsertBefore() is
  279. // subsequently to use 'NextSibling' which is
  280. // faster than 'PreviousSibling' (these children are
  281. // forward-only linked list).
  282. XmlNode argNode = null;
  283. if(refChild != null)
  284. argNode = refChild.NextSibling;
  285. else if(ChildNodes.Count > 0)
  286. argNode = FirstChild;
  287. return InsertBefore (newChild, argNode);
  288. }
  289. public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
  290. {
  291. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  292. if (NodeType != XmlNodeType.Element &&
  293. NodeType != XmlNodeType.Attribute &&
  294. NodeType != XmlNodeType.Document &&
  295. NodeType != XmlNodeType.DocumentFragment)
  296. throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
  297. switch (NodeType) {
  298. case XmlNodeType.Attribute:
  299. switch (newChild.NodeType) {
  300. case XmlNodeType.Text:
  301. case XmlNodeType.EntityReference:
  302. break;
  303. default:
  304. throw new ArgumentException (String.Format (
  305. "Cannot insert specified type of node {0} as a child of this node {0}.",
  306. newChild.NodeType, NodeType));
  307. }
  308. break;
  309. case XmlNodeType.Element:
  310. switch (newChild.NodeType) {
  311. case XmlNodeType.Attribute:
  312. case XmlNodeType.Document:
  313. case XmlNodeType.DocumentType:
  314. case XmlNodeType.Entity:
  315. case XmlNodeType.Notation:
  316. case XmlNodeType.XmlDeclaration:
  317. throw new ArgumentException ("Cannot insert specified type of node as a child of this node.");
  318. }
  319. break;
  320. }
  321. if (IsReadOnly)
  322. throw new ArgumentException ("The specified node is readonly.");
  323. if (newChild.OwnerDocument != ownerDoc)
  324. throw new ArgumentException ("Can't append a node created by another document.");
  325. if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
  326. throw new ArgumentException ("argument nodes are on the different documents.");
  327. // This check is done by MS.NET 1.0, but isn't done for MS.NET 1.1.
  328. // Skip this check in the meantime...
  329. // if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement))
  330. // throw new XmlException ("multiple document element not allowed.");
  331. // checking validity finished. then appending...
  332. return insertBeforeIntern (newChild, refChild);
  333. }
  334. internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
  335. {
  336. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  337. ownerDoc.onNodeInserting (newChild, this);
  338. if(newChild.ParentNode != null)
  339. newChild.ParentNode.RemoveChild (newChild);
  340. if(newChild.NodeType == XmlNodeType.DocumentFragment) {
  341. int x = newChild.ChildNodes.Count;
  342. for(int i=0; i<x; i++) {
  343. XmlNode n = newChild.ChildNodes [0];
  344. this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  345. }
  346. }
  347. else {
  348. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  349. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  350. newLinkedChild.parentNode = this;
  351. if(refChild == null) {
  352. // append last, so:
  353. // * set nextSibling of previous lastchild to newChild
  354. // * set lastchild = newChild
  355. // * set next of newChild to firstChild
  356. if(LastLinkedChild != null) {
  357. XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
  358. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  359. LastLinkedChild = newLinkedChild;
  360. newLinkedChild.NextLinkedSibling = formerFirst;
  361. }
  362. else {
  363. LastLinkedChild = newLinkedChild;
  364. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  365. }
  366. }
  367. else {
  368. // append not last, so:
  369. // * if newchild is first, then set next of lastchild is newChild.
  370. // otherwise, set next of previous sibling to newChild
  371. // * set next of newChild to refChild
  372. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  373. if(prev == null)
  374. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  375. else
  376. prev.NextLinkedSibling = newLinkedChild;
  377. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  378. }
  379. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  380. }
  381. return newChild;
  382. }
  383. public virtual void Normalize ()
  384. {
  385. // if (tmpBuilder == null)
  386. tmpBuilder = new StringBuilder ();
  387. // tmpBuilder.Length = 0;
  388. int count = this.ChildNodes.Count;
  389. int start = 0;
  390. for (int i = 0; i < count; i++) {
  391. XmlNode c = ChildNodes [i];
  392. switch (c.NodeType) {
  393. case XmlNodeType.Text:
  394. case XmlNodeType.Whitespace:
  395. case XmlNodeType.SignificantWhitespace:
  396. tmpBuilder.Append (c.Value);
  397. break;
  398. default:
  399. c.Normalize ();
  400. NormalizeRange (start, i);
  401. // Continue to normalize from next node.
  402. start = i + 1;
  403. break;
  404. }
  405. }
  406. if (start < count) {
  407. NormalizeRange (start, count);
  408. }
  409. tmpBuilder = null;
  410. }
  411. private void NormalizeRange (int start, int i)
  412. {
  413. int keepPos = -1;
  414. // If Texts and Whitespaces are mixed, Text takes precedence to remain.
  415. // i.e. Whitespace should be removed.
  416. for (int j = start; j < i; j++) {
  417. XmlNode keep = ChildNodes [j];
  418. if (keep.NodeType == XmlNodeType.Text) {
  419. keepPos = j;
  420. break;
  421. }
  422. else if (keep.NodeType == XmlNodeType.SignificantWhitespace)
  423. keepPos = j;
  424. // but don't break up to find Text nodes.
  425. }
  426. // But if no Texts and one or more Whitespaces, then the first
  427. if (keepPos < 0 && i > start)
  428. keepPos = 0;
  429. if (keepPos >= 0) {
  430. for (int del = start; del < keepPos; del++)
  431. RemoveChild (ChildNodes [del]);
  432. for (int del = keepPos + 1; del < i; del++)
  433. RemoveChild (ChildNodes [del]);
  434. }
  435. ChildNodes [keepPos].Value = tmpBuilder.ToString ();
  436. tmpBuilder.Length = 0;
  437. }
  438. public virtual XmlNode PrependChild (XmlNode newChild)
  439. {
  440. return InsertAfter (newChild, null);
  441. }
  442. public virtual void RemoveAll ()
  443. {
  444. if (Attributes != null)
  445. Attributes.RemoveAll ();
  446. XmlNode next = null;
  447. for (XmlNode node = FirstChild; node != null; node = next) {
  448. next = node.NextSibling;
  449. RemoveChild (node);
  450. }
  451. }
  452. public virtual XmlNode RemoveChild (XmlNode oldChild)
  453. {
  454. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  455. if(oldChild.ParentNode != this)
  456. throw new XmlException ("specified child is not child of this node.");
  457. ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
  458. if (NodeType != XmlNodeType.Attribute &&
  459. NodeType != XmlNodeType.Element &&
  460. NodeType != XmlNodeType.Document &&
  461. NodeType != XmlNodeType.DocumentFragment)
  462. throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
  463. if (IsReadOnly)
  464. throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
  465. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  466. // If there is only one children, simply clear.
  467. LastLinkedChild = null;
  468. else {
  469. XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
  470. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  471. XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
  472. while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
  473. Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  474. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  475. if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  476. throw new ArgumentException ();
  477. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  478. // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
  479. if (oldLinkedChild.NextLinkedSibling == firstChild)
  480. this.LastLinkedChild = beforeLinkedChild;
  481. oldLinkedChild.NextLinkedSibling = null;
  482. }
  483. ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
  484. oldChild.parentNode = null; // clear parent 'after' above logic.
  485. return oldChild;
  486. }
  487. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  488. {
  489. if(oldChild.ParentNode != this)
  490. throw new InvalidOperationException ("oldChild is not a child of this node.");
  491. XmlNode parent = this.ParentNode;
  492. while(parent != null) {
  493. if(newChild == parent)
  494. throw new InvalidOperationException ("newChild is ancestor of this node.");
  495. parent = parent.ParentNode;
  496. }
  497. foreach(XmlNode n in ChildNodes) {
  498. if(n == oldChild) {
  499. XmlNode prev = oldChild.PreviousSibling;
  500. RemoveChild (oldChild);
  501. InsertAfter (newChild, prev);
  502. break;
  503. }
  504. }
  505. return oldChild;
  506. }
  507. public XmlNodeList SelectNodes (string xpath)
  508. {
  509. return SelectNodes (xpath, null);
  510. }
  511. [MonoTODO ("return nodes in document order")]
  512. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  513. {
  514. XPathNavigator nav = CreateNavigator ();
  515. XPathExpression expr = nav.Compile (xpath);
  516. if (nsmgr != null)
  517. expr.SetContext (nsmgr);
  518. XPathNodeIterator iter = nav.Select (expr);
  519. ArrayList rgNodes = new ArrayList ();
  520. while (iter.MoveNext ())
  521. {
  522. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  523. }
  524. return new XmlNodeArrayList (rgNodes);
  525. }
  526. public XmlNode SelectSingleNode (string xpath)
  527. {
  528. return SelectSingleNode (xpath, null);
  529. }
  530. [MonoTODO]
  531. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  532. {
  533. XPathNavigator nav = CreateNavigator ();
  534. XPathExpression expr = nav.Compile (xpath);
  535. if (nsmgr != null)
  536. expr.SetContext (nsmgr);
  537. XPathNodeIterator iter = nav.Select (expr);
  538. if (!iter.MoveNext ())
  539. return null;
  540. return ((XmlDocumentNavigator) iter.Current).Node;
  541. }
  542. [MonoTODO]
  543. public virtual bool Supports (string feature, string version)
  544. {
  545. throw new NotImplementedException ();
  546. }
  547. public abstract void WriteContentTo (XmlWriter w);
  548. public abstract void WriteTo (XmlWriter w);
  549. // It parses this and all the ancestor elements,
  550. // find 'xmlns' declarations, stores and then return them.
  551. // TODO: tests
  552. internal XmlNamespaceManager ConstructNamespaceManager ()
  553. {
  554. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  555. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  556. XmlElement el = null;
  557. switch(this.NodeType) {
  558. case XmlNodeType.Attribute:
  559. el = ((XmlAttribute)this).OwnerElement;
  560. break;
  561. case XmlNodeType.Element:
  562. el = this as XmlElement;
  563. break;
  564. default:
  565. el = this.ParentNode as XmlElement;
  566. break;
  567. }
  568. while(el != null) {
  569. foreach(XmlAttribute attr in el.Attributes) {
  570. if(attr.Prefix == "xmlns") {
  571. if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
  572. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  573. } else if(attr.Name == "xmlns") {
  574. if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
  575. nsmgr.AddNamespace (String.Empty, attr.Value);
  576. }
  577. }
  578. // When reached to document, then it will set null value :)
  579. el = el.ParentNode as XmlElement;
  580. }
  581. return nsmgr;
  582. }
  583. #endregion
  584. }
  585. }