XmlNode.cs 16 KB

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