XmlNode.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. 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. [MonoTODO]
  384. public virtual void Normalize ()
  385. {
  386. throw new NotImplementedException ();
  387. }
  388. public virtual XmlNode PrependChild (XmlNode newChild)
  389. {
  390. return InsertAfter (newChild, null);
  391. }
  392. public virtual void RemoveAll ()
  393. {
  394. if (Attributes != null)
  395. Attributes.RemoveAll ();
  396. XmlNode next = null;
  397. for (XmlNode node = FirstChild; node != null; node = next) {
  398. next = node.NextSibling;
  399. RemoveChild (node);
  400. }
  401. }
  402. public virtual XmlNode RemoveChild (XmlNode oldChild)
  403. {
  404. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  405. if(oldChild.ParentNode != this)
  406. throw new XmlException ("specified child is not child of this node.");
  407. ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
  408. if (NodeType != XmlNodeType.Attribute &&
  409. NodeType != XmlNodeType.Element &&
  410. NodeType != XmlNodeType.Document &&
  411. NodeType != XmlNodeType.DocumentFragment)
  412. throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
  413. if (IsReadOnly)
  414. throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
  415. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  416. // If there is only one children, simply clear.
  417. LastLinkedChild = null;
  418. else {
  419. XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
  420. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  421. XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
  422. while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
  423. Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  424. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  425. if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  426. throw new ArgumentException ();
  427. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  428. // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
  429. if (oldLinkedChild.NextLinkedSibling == firstChild)
  430. this.LastLinkedChild = beforeLinkedChild;
  431. oldLinkedChild.NextLinkedSibling = null;
  432. }
  433. ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
  434. oldChild.parentNode = null; // clear parent 'after' above logic.
  435. return oldChild;
  436. }
  437. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  438. {
  439. if(oldChild.ParentNode != this)
  440. throw new InvalidOperationException ("oldChild is not a child of this node.");
  441. XmlNode parent = this.ParentNode;
  442. while(parent != null) {
  443. if(newChild == parent)
  444. throw new InvalidOperationException ("newChild is ancestor of this node.");
  445. parent = parent.ParentNode;
  446. }
  447. foreach(XmlNode n in ChildNodes) {
  448. if(n == oldChild) {
  449. XmlNode prev = oldChild.PreviousSibling;
  450. RemoveChild (oldChild);
  451. InsertAfter (newChild, prev);
  452. break;
  453. }
  454. }
  455. return oldChild;
  456. }
  457. public XmlNodeList SelectNodes (string xpath)
  458. {
  459. return SelectNodes (xpath, null);
  460. }
  461. [MonoTODO ("return nodes in document order")]
  462. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  463. {
  464. XPathNavigator nav = CreateNavigator ();
  465. XPathExpression expr = nav.Compile (xpath);
  466. if (nsmgr != null)
  467. expr.SetContext (nsmgr);
  468. XPathNodeIterator iter = nav.Select (expr);
  469. ArrayList rgNodes = new ArrayList ();
  470. while (iter.MoveNext ())
  471. {
  472. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  473. }
  474. return new XmlNodeArrayList (rgNodes);
  475. }
  476. public XmlNode SelectSingleNode (string xpath)
  477. {
  478. return SelectSingleNode (xpath, null);
  479. }
  480. [MonoTODO]
  481. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  482. {
  483. XPathNavigator nav = CreateNavigator ();
  484. XPathExpression expr = nav.Compile (xpath);
  485. if (nsmgr != null)
  486. expr.SetContext (nsmgr);
  487. XPathNodeIterator iter = nav.Select (expr);
  488. if (!iter.MoveNext ())
  489. return null;
  490. return ((XmlDocumentNavigator) iter.Current).Node;
  491. }
  492. [MonoTODO]
  493. public virtual bool Supports (string feature, string version)
  494. {
  495. throw new NotImplementedException ();
  496. }
  497. public abstract void WriteContentTo (XmlWriter w);
  498. public abstract void WriteTo (XmlWriter w);
  499. // It parses this and all the ancestor elements,
  500. // find 'xmlns' declarations, stores and then return them.
  501. // TODO: tests
  502. internal XmlNamespaceManager ConstructNamespaceManager ()
  503. {
  504. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  505. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  506. XmlElement el = null;
  507. switch(this.NodeType) {
  508. case XmlNodeType.Attribute:
  509. el = ((XmlAttribute)this).OwnerElement;
  510. break;
  511. case XmlNodeType.Element:
  512. el = this as XmlElement;
  513. break;
  514. default:
  515. el = this.ParentNode as XmlElement;
  516. break;
  517. }
  518. while(el != null) {
  519. foreach(XmlAttribute attr in el.Attributes) {
  520. if(attr.Prefix == "xmlns") {
  521. if (nsmgr.LookupNamespace (attr.LocalName) != attr.Value)
  522. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  523. } else if(attr.Name == "xmlns") {
  524. if(nsmgr.LookupNamespace (String.Empty) != attr.Value)
  525. nsmgr.AddNamespace (String.Empty, attr.Value);
  526. }
  527. }
  528. // When reached to document, then it will set null value :)
  529. el = el.ParentNode as XmlElement;
  530. }
  531. return nsmgr;
  532. }
  533. #endregion
  534. }
  535. }