XmlNode.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. string result = (ParentNode != null) ? ParentNode.BaseURI : OwnerDocument.BaseURI;
  39. try {
  40. Uri test = new Uri(result);
  41. }
  42. catch {
  43. result = "file://" + result;
  44. }
  45. return result;
  46. }
  47. }
  48. public virtual XmlNodeList ChildNodes {
  49. get {
  50. return new XmlNodeListChildren (this);
  51. }
  52. }
  53. public virtual XmlNode FirstChild {
  54. get {
  55. if (LastChild != null) {
  56. return LastLinkedChild.NextLinkedSibling;
  57. }
  58. else {
  59. return null;
  60. }
  61. }
  62. }
  63. public virtual bool HasChildNodes {
  64. get { return LastChild != null; }
  65. }
  66. [MonoTODO("confirm whether this way is right for each not-overriden types.")]
  67. public virtual string InnerText {
  68. get {
  69. StringBuilder builder = new StringBuilder ();
  70. AppendChildValues (this, builder);
  71. return builder.ToString ();
  72. }
  73. set { throw new NotImplementedException (); }
  74. }
  75. private void AppendChildValues (XmlNode parent, StringBuilder builder)
  76. {
  77. XmlNode node = parent.FirstChild;
  78. while (node != null) {
  79. if (node.NodeType == XmlNodeType.Text)
  80. builder.Append (node.Value);
  81. AppendChildValues (node, builder);
  82. node = node.NextSibling;
  83. }
  84. }
  85. [MonoTODO("Setter.")]
  86. public virtual string InnerXml {
  87. get {
  88. StringWriter sw = new StringWriter ();
  89. XmlTextWriter xtw = new XmlTextWriter (sw);
  90. WriteContentTo (xtw);
  91. return sw.GetStringBuilder ().ToString ();
  92. }
  93. set { throw new NotImplementedException (); }
  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. return (XPathNodeType) (-1);
  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.GetStringBuilder ().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. return new XmlDocumentNavigator (this);
  211. }
  212. public IEnumerator GetEnumerator ()
  213. {
  214. return new XmlNodeListChildren (this).GetEnumerator ();
  215. }
  216. [MonoTODO("performance problem.")]
  217. public virtual string GetNamespaceOfPrefix (string prefix)
  218. {
  219. XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
  220. return nsmgr.LookupNamespace (prefix);
  221. }
  222. [MonoTODO("performance problem.")]
  223. public virtual string GetPrefixOfNamespace (string namespaceURI)
  224. {
  225. XmlNamespaceManager nsmgr = ConstructNamespaceManager ();
  226. string ns = nsmgr.LookupPrefix (namespaceURI);
  227. return (ns != null) ? ns : String.Empty;
  228. }
  229. object ICloneable.Clone ()
  230. {
  231. return Clone ();
  232. }
  233. IEnumerator IEnumerable.GetEnumerator ()
  234. {
  235. return GetEnumerator ();
  236. }
  237. public virtual XmlNode InsertAfter (XmlNode newChild, XmlNode refChild)
  238. {
  239. // I assume that insertAfter(n1, n2) equals to InsertBefore(n1, n2.PreviousSibling).
  240. // I took this way because rather than calling InsertAfter() from InsertBefore()
  241. // because current implementation of 'NextSibling' looks faster than 'PreviousSibling'.
  242. XmlNode argNode = null;
  243. if(refChild != null)
  244. argNode = refChild.NextSibling;
  245. else if(ChildNodes.Count > 0)
  246. argNode = FirstChild;
  247. return InsertBefore (newChild, argNode);
  248. }
  249. [MonoTODO("If inserted node is entity reference, then check conforming entity. Wait for DTD implementation.")]
  250. public virtual XmlNode InsertBefore (XmlNode newChild, XmlNode refChild)
  251. {
  252. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  253. if (NodeType == XmlNodeType.Document ||
  254. NodeType == XmlNodeType.Element ||
  255. NodeType == XmlNodeType.Attribute ||
  256. NodeType == XmlNodeType.DocumentFragment) {
  257. if (IsReadOnly)
  258. throw new ArgumentException ("The specified node is readonly.");
  259. if (newChild.OwnerDocument != ownerDoc)
  260. throw new ArgumentException ("Can't append a node created by another document.");
  261. if (refChild != null && newChild.OwnerDocument != refChild.OwnerDocument)
  262. throw new ArgumentException ("argument nodes are on the different documents.");
  263. // This check is done by MS.NET 1.0, but isn't done for MS.NET 1.1.
  264. // Skip this check in the meantime...
  265. // if(this == ownerDoc && ownerDoc.DocumentElement != null && (newChild is XmlElement))
  266. // throw new XmlException ("multiple document element not allowed.");
  267. // checking validity finished. then appending...
  268. return insertBeforeIntern (newChild, refChild);
  269. }
  270. else
  271. throw new InvalidOperationException (String.Format ("current node {0} is not allowed to have any children.", NodeType));
  272. }
  273. internal XmlNode insertBeforeIntern (XmlNode newChild, XmlNode refChild)
  274. {
  275. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  276. ownerDoc.onNodeInserting (newChild, this);
  277. if(newChild.ParentNode != null)
  278. newChild.ParentNode.RemoveChild (newChild);
  279. if(newChild.NodeType == XmlNodeType.DocumentFragment) {
  280. int x = newChild.ChildNodes.Count;
  281. for(int i=0; i<x; i++) {
  282. XmlNode n = newChild.ChildNodes [0];
  283. this.InsertBefore (n, refChild); // recursively invokes events. (It is compatible with MS implementation.)
  284. }
  285. }
  286. else {
  287. XmlLinkedNode newLinkedChild = (XmlLinkedNode) newChild;
  288. XmlLinkedNode lastLinkedChild = LastLinkedChild;
  289. newLinkedChild.parentNode = this;
  290. if(refChild == null) {
  291. // append last, so:
  292. // * set nextSibling of previous lastchild to newChild
  293. // * set lastchild = newChild
  294. // * set next of newChild to firstChild
  295. if(LastLinkedChild != null) {
  296. XmlLinkedNode formerFirst = FirstChild as XmlLinkedNode;
  297. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  298. LastLinkedChild = newLinkedChild;
  299. newLinkedChild.NextLinkedSibling = formerFirst;
  300. }
  301. else {
  302. LastLinkedChild = newLinkedChild;
  303. LastLinkedChild.NextLinkedSibling = newLinkedChild; // FirstChild
  304. }
  305. }
  306. else {
  307. // append not last, so:
  308. // * if newchild is first, then set next of lastchild is newChild.
  309. // otherwise, set next of previous sibling to newChild
  310. // * set next of newChild to refChild
  311. XmlLinkedNode prev = refChild.PreviousSibling as XmlLinkedNode;
  312. if(prev == null)
  313. LastLinkedChild.NextLinkedSibling = newLinkedChild;
  314. else
  315. prev.NextLinkedSibling = newLinkedChild;
  316. newLinkedChild.NextLinkedSibling = refChild as XmlLinkedNode;
  317. }
  318. ownerDoc.onNodeInserted (newChild, newChild.ParentNode);
  319. }
  320. return newChild;
  321. }
  322. [MonoTODO]
  323. public virtual void Normalize ()
  324. {
  325. throw new NotImplementedException ();
  326. }
  327. public virtual XmlNode PrependChild (XmlNode newChild)
  328. {
  329. return InsertAfter (newChild, null);
  330. }
  331. public virtual void RemoveAll ()
  332. {
  333. XmlNode next = null;
  334. for (XmlNode node = FirstChild; node != null; node = next) {
  335. next = node.NextSibling;
  336. RemoveChild (node);
  337. }
  338. }
  339. public virtual XmlNode RemoveChild (XmlNode oldChild)
  340. {
  341. XmlDocument ownerDoc = (NodeType == XmlNodeType.Document) ? (XmlDocument)this : OwnerDocument;
  342. if(oldChild.ParentNode != this)
  343. throw new XmlException ("specified child is not child of this node.");
  344. ownerDoc.onNodeRemoving (oldChild, oldChild.ParentNode);
  345. if (NodeType != XmlNodeType.Attribute &&
  346. NodeType != XmlNodeType.Element &&
  347. NodeType != XmlNodeType.Document &&
  348. NodeType != XmlNodeType.DocumentFragment)
  349. throw new ArgumentException (String.Format ("This {0} node cannot remove child.", NodeType));
  350. if (IsReadOnly)
  351. throw new ArgumentException (String.Format ("This {0} node is read only.", NodeType));
  352. if (Object.ReferenceEquals (LastLinkedChild, LastLinkedChild.NextLinkedSibling) && Object.ReferenceEquals (LastLinkedChild, oldChild))
  353. // If there is only one children, simply clear.
  354. LastLinkedChild = null;
  355. else {
  356. XmlLinkedNode oldLinkedChild = (XmlLinkedNode) oldChild;
  357. XmlLinkedNode beforeLinkedChild = LastLinkedChild;
  358. XmlLinkedNode firstChild = (XmlLinkedNode) FirstChild;
  359. while (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, LastLinkedChild) == false &&
  360. Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  361. beforeLinkedChild = beforeLinkedChild.NextLinkedSibling;
  362. if (Object.ReferenceEquals (beforeLinkedChild.NextLinkedSibling, oldLinkedChild) == false)
  363. throw new ArgumentException ();
  364. beforeLinkedChild.NextLinkedSibling = oldLinkedChild.NextLinkedSibling;
  365. // Each derived class may have its own LastLinkedChild, so we must set it explicitly.
  366. if (oldLinkedChild.NextLinkedSibling == firstChild)
  367. this.LastLinkedChild = beforeLinkedChild;
  368. oldLinkedChild.NextLinkedSibling = null;
  369. }
  370. ownerDoc.onNodeRemoved (oldChild, oldChild.ParentNode);
  371. oldChild.parentNode = null; // clear parent 'after' above logic.
  372. return oldChild;
  373. }
  374. public virtual XmlNode ReplaceChild (XmlNode newChild, XmlNode oldChild)
  375. {
  376. if(oldChild.ParentNode != this)
  377. throw new InvalidOperationException ("oldChild is not a child of this node.");
  378. XmlNode parent = this.ParentNode;
  379. while(parent != null) {
  380. if(newChild == parent)
  381. throw new InvalidOperationException ("newChild is ancestor of this node.");
  382. parent = parent.ParentNode;
  383. }
  384. foreach(XmlNode n in ChildNodes) {
  385. if(n == oldChild) {
  386. XmlNode prev = oldChild.PreviousSibling;
  387. RemoveChild (oldChild);
  388. InsertAfter (newChild, prev);
  389. break;
  390. }
  391. }
  392. return oldChild;
  393. }
  394. public XmlNodeList SelectNodes (string xpath)
  395. {
  396. return SelectNodes (xpath, null);
  397. }
  398. [MonoTODO]
  399. public XmlNodeList SelectNodes (string xpath, XmlNamespaceManager nsmgr)
  400. {
  401. XPathNavigator nav = CreateNavigator ();
  402. XPathExpression expr = nav.Compile (xpath);
  403. if (nsmgr != null)
  404. expr.SetContext (nsmgr);
  405. XPathNodeIterator iter = nav.Select (expr);
  406. ArrayList rgNodes = new ArrayList ();
  407. while (iter.MoveNext ())
  408. {
  409. rgNodes.Add (((XmlDocumentNavigator) iter.Current).Node);
  410. }
  411. return new XmlNodeArrayList (rgNodes);
  412. }
  413. public XmlNode SelectSingleNode (string xpath)
  414. {
  415. return SelectSingleNode (xpath, null);
  416. }
  417. [MonoTODO]
  418. public XmlNode SelectSingleNode (string xpath, XmlNamespaceManager nsmgr)
  419. {
  420. XPathNavigator nav = CreateNavigator ();
  421. XPathExpression expr = nav.Compile (xpath);
  422. if (nsmgr != null)
  423. expr.SetContext (nsmgr);
  424. XPathNodeIterator iter = nav.Select (expr);
  425. if (!iter.MoveNext ())
  426. return null;
  427. return ((XmlDocumentNavigator) iter.Current).Node;
  428. }
  429. internal void SetParentNode (XmlNode parent)
  430. {
  431. parentNode = parent;
  432. }
  433. [MonoTODO]
  434. public virtual bool Supports (string feature, string version)
  435. {
  436. throw new NotImplementedException ();
  437. }
  438. public abstract void WriteContentTo (XmlWriter w);
  439. public abstract void WriteTo (XmlWriter w);
  440. // It parses this and all the ancestor elements,
  441. // find 'xmlns' declarations, stores and then return them.
  442. // TODO: tests
  443. internal XmlNamespaceManager ConstructNamespaceManager ()
  444. {
  445. XmlDocument doc = this is XmlDocument ? (XmlDocument)this : this.OwnerDocument;
  446. XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
  447. XmlElement el = null;
  448. switch(this.NodeType) {
  449. case XmlNodeType.Attribute:
  450. el = ((XmlAttribute)this).OwnerElement;
  451. break;
  452. case XmlNodeType.Element:
  453. el = this as XmlElement;
  454. break;
  455. default:
  456. el = this.ParentNode as XmlElement;
  457. break;
  458. }
  459. while(el != null) {
  460. foreach(XmlAttribute attr in el.Attributes) {
  461. if(attr.Prefix == "xmlns") {
  462. if (nsmgr.LookupNamespace (attr.LocalName) == null)
  463. nsmgr.AddNamespace (attr.LocalName, attr.Value);
  464. } else if(attr.Name == "xmlns") {
  465. if(nsmgr.LookupNamespace (String.Empty) == null)
  466. nsmgr.AddNamespace (String.Empty, attr.Value);
  467. }
  468. }
  469. // When reached to document, then it will set null value :)
  470. el = el.ParentNode as XmlElement;
  471. }
  472. return nsmgr;
  473. }
  474. #endregion
  475. }
  476. }