XmlDocumentTests.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // System.Xml.XmlDocumentTests
  2. //
  3. // Authors:
  4. // Jason Diamond <[email protected]>
  5. // Kral Ferch <[email protected]>
  6. // Martin Willemoes Hansen <[email protected]>
  7. //
  8. // (C) 2002 Jason Diamond, Kral Ferch
  9. // (C) 2003 Martin Willemoes Hansen
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.Xml;
  14. using System.IO;
  15. using System.Text;
  16. using NUnit.Framework;
  17. namespace MonoTests.System.Xml
  18. {
  19. [TestFixture]
  20. public class XmlDocumentTests : Assertion
  21. {
  22. private XmlDocument document;
  23. private ArrayList eventStrings = new ArrayList();
  24. // These Event* methods support the TestEventNode* Tests in this file.
  25. // Most of them are event handlers for the XmlNodeChangedEventHandler
  26. // delegate.
  27. private void EventStringAdd(string eventName, XmlNodeChangedEventArgs e)
  28. {
  29. string oldParent = (e.OldParent != null) ? e.OldParent.Name : "<none>";
  30. string newParent = (e.NewParent != null) ? e.NewParent.Name : "<none>";
  31. eventStrings.Add (String.Format ("{0}, {1}, {2}, {3}, {4}", eventName, e.Action.ToString (), e.Node.OuterXml, oldParent, newParent));
  32. }
  33. private void EventNodeChanged(Object sender, XmlNodeChangedEventArgs e)
  34. {
  35. EventStringAdd ("NodeChanged", e);
  36. }
  37. private void EventNodeChanging (Object sender, XmlNodeChangedEventArgs e)
  38. {
  39. EventStringAdd ("NodeChanging", e);
  40. }
  41. private void EventNodeChangingException (Object sender, XmlNodeChangedEventArgs e)
  42. {
  43. throw new Exception ("don't change the value.");
  44. }
  45. private void EventNodeInserted(Object sender, XmlNodeChangedEventArgs e)
  46. {
  47. EventStringAdd ("NodeInserted", e);
  48. }
  49. private void EventNodeInserting(Object sender, XmlNodeChangedEventArgs e)
  50. {
  51. EventStringAdd ("NodeInserting", e);
  52. }
  53. private void EventNodeInsertingException(Object sender, XmlNodeChangedEventArgs e)
  54. {
  55. throw new Exception ("don't insert the element.");
  56. }
  57. private void EventNodeRemoved(Object sender, XmlNodeChangedEventArgs e)
  58. {
  59. EventStringAdd ("NodeRemoved", e);
  60. }
  61. private void EventNodeRemoving(Object sender, XmlNodeChangedEventArgs e)
  62. {
  63. EventStringAdd ("NodeRemoving", e);
  64. }
  65. private void EventNodeRemovingException(Object sender, XmlNodeChangedEventArgs e)
  66. {
  67. throw new Exception ("don't remove the element.");
  68. }
  69. [SetUp]
  70. public void GetReady ()
  71. {
  72. document = new XmlDocument ();
  73. document.PreserveWhitespace = true;
  74. }
  75. [Test]
  76. public void CreateNodeNodeTypeNameEmptyParams ()
  77. {
  78. XmlNode node;
  79. try {
  80. node = document.CreateNode (null, null, null);
  81. Fail ("Expected an ArgumentException to be thrown.");
  82. } catch (ArgumentException) {}
  83. try {
  84. node = document.CreateNode ("attribute", null, null);
  85. Fail ("Expected a NullReferenceException to be thrown.");
  86. } catch (NullReferenceException) {}
  87. try {
  88. node = document.CreateNode ("attribute", "", null);
  89. Fail ("Expected an ArgumentException to be thrown.");
  90. } catch (ArgumentException) {}
  91. try {
  92. node = document.CreateNode ("element", null, null);
  93. Fail ("Expected a NullReferenceException to be thrown.");
  94. } catch (NullReferenceException) {}
  95. try {
  96. node = document.CreateNode ("element", "", null);
  97. Fail ("Expected an ArgumentException to be thrown.");
  98. } catch (ArgumentException) {}
  99. try {
  100. node = document.CreateNode ("entityreference", null, null);
  101. Fail ("Expected a NullReferenceException to be thrown.");
  102. } catch (NullReferenceException) {}
  103. }
  104. [Test]
  105. public void CreateNodeInvalidXmlNodeType ()
  106. {
  107. XmlNode node;
  108. try {
  109. node = document.CreateNode (XmlNodeType.EndElement, null, null);
  110. Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
  111. } catch (ArgumentOutOfRangeException) {}
  112. try {
  113. node = document.CreateNode (XmlNodeType.EndEntity, null, null);
  114. Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
  115. } catch (ArgumentOutOfRangeException) {}
  116. try {
  117. node = document.CreateNode (XmlNodeType.Entity, null, null);
  118. Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
  119. } catch (ArgumentOutOfRangeException) {}
  120. try {
  121. node = document.CreateNode (XmlNodeType.None, null, null);
  122. Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
  123. } catch (ArgumentOutOfRangeException) {}
  124. try {
  125. node = document.CreateNode (XmlNodeType.Notation, null, null);
  126. Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
  127. } catch (ArgumentOutOfRangeException) {}
  128. // TODO: undocumented allowable type.
  129. node = document.CreateNode (XmlNodeType.XmlDeclaration, null, null);
  130. AssertEquals (XmlNodeType.XmlDeclaration, node.NodeType);
  131. }
  132. [Test]
  133. public void CreateNodeWhichParamIsUsed ()
  134. {
  135. XmlNode node;
  136. // No constructor params for Document, DocumentFragment.
  137. node = document.CreateNode (XmlNodeType.CDATA, "a", "b", "c");
  138. AssertEquals (String.Empty, ((XmlCDataSection)node).Value);
  139. node = document.CreateNode (XmlNodeType.Comment, "a", "b", "c");
  140. AssertEquals (String.Empty, ((XmlComment)node).Value);
  141. node = document.CreateNode (XmlNodeType.DocumentType, "a", "b", "c");
  142. AssertNull (((XmlDocumentType)node).Value);
  143. // TODO: add this back in to test when it's implemented.
  144. // node = document.CreateNode (XmlNodeType.EntityReference, "a", "b", "c");
  145. // AssertNull (((XmlEntityReference)node).Value);
  146. node = document.CreateNode (XmlNodeType.ProcessingInstruction, "a", "b", "c");
  147. AssertEquals (String.Empty, ((XmlProcessingInstruction)node).Value);
  148. node = document.CreateNode (XmlNodeType.SignificantWhitespace, "a", "b", "c");
  149. AssertEquals (String.Empty, ((XmlSignificantWhitespace)node).Value);
  150. node = document.CreateNode (XmlNodeType.Text, "a", "b", "c");
  151. AssertEquals (String.Empty, ((XmlText)node).Value);
  152. node = document.CreateNode (XmlNodeType.Whitespace, "a", "b", "c");
  153. AssertEquals (String.Empty, ((XmlWhitespace)node).Value);
  154. node = document.CreateNode (XmlNodeType.XmlDeclaration, "a", "b", "c");
  155. AssertEquals ("version=\"1.0\"", ((XmlDeclaration)node).Value);
  156. }
  157. [Test]
  158. public void CreateNodeNodeTypeName ()
  159. {
  160. XmlNode node;
  161. try {
  162. node = document.CreateNode ("foo", null, null);
  163. Fail ("Expected an ArgumentException to be thrown.");
  164. } catch (ArgumentException) {}
  165. node = document.CreateNode("attribute", "foo", null);
  166. AssertEquals (XmlNodeType.Attribute, node.NodeType);
  167. node = document.CreateNode("cdatasection", null, null);
  168. AssertEquals (XmlNodeType.CDATA, node.NodeType);
  169. node = document.CreateNode("comment", null, null);
  170. AssertEquals (XmlNodeType.Comment, node.NodeType);
  171. node = document.CreateNode("document", null, null);
  172. AssertEquals (XmlNodeType.Document, node.NodeType);
  173. // TODO: test which constructor this ended up calling,
  174. // i.e. reuse underlying NameTable or not?
  175. // TODO: add this back in to test when it's implemented.
  176. // node = document.CreateNode("documentfragment", null, null);
  177. // AssertEquals (XmlNodeType.DocumentFragment, node.NodeType);
  178. node = document.CreateNode("documenttype", null, null);
  179. AssertEquals (XmlNodeType.DocumentType, node.NodeType);
  180. node = document.CreateNode("element", "foo", null);
  181. AssertEquals (XmlNodeType.Element, node.NodeType);
  182. // TODO: add this back in to test when it's implemented.
  183. // node = document.CreateNode("entityreference", "foo", null);
  184. // AssertEquals (XmlNodeType.EntityReference, node.NodeType);
  185. node = document.CreateNode("processinginstruction", null, null);
  186. AssertEquals (XmlNodeType.ProcessingInstruction, node.NodeType);
  187. node = document.CreateNode("significantwhitespace", null, null);
  188. AssertEquals (XmlNodeType.SignificantWhitespace, node.NodeType);
  189. node = document.CreateNode("text", null, null);
  190. AssertEquals (XmlNodeType.Text, node.NodeType);
  191. node = document.CreateNode("whitespace", null, null);
  192. AssertEquals (XmlNodeType.Whitespace, node.NodeType);
  193. }
  194. [Test]
  195. public void DocumentElement ()
  196. {
  197. AssertNull (document.DocumentElement);
  198. XmlElement element = document.CreateElement ("foo", "bar", "http://foo/");
  199. AssertNotNull (element);
  200. AssertEquals ("foo", element.Prefix);
  201. AssertEquals ("bar", element.LocalName);
  202. AssertEquals ("http://foo/", element.NamespaceURI);
  203. AssertEquals ("foo:bar", element.Name);
  204. AssertSame (element, document.AppendChild (element));
  205. AssertSame (element, document.DocumentElement);
  206. }
  207. [Test]
  208. public void DocumentEmpty()
  209. {
  210. AssertEquals ("Incorrect output for empty document.", "", document.OuterXml);
  211. }
  212. [Test]
  213. public void EventNodeChanged()
  214. {
  215. XmlElement element;
  216. XmlComment comment;
  217. document.NodeChanged += new XmlNodeChangedEventHandler (this.EventNodeChanged);
  218. // Node that is part of the document.
  219. document.AppendChild (document.CreateElement ("foo"));
  220. comment = document.CreateComment ("bar");
  221. document.DocumentElement.AppendChild (comment);
  222. AssertEquals ("<!--bar-->", document.DocumentElement.InnerXml);
  223. comment.Value = "baz";
  224. Assert (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo"));
  225. AssertEquals ("<!--baz-->", document.DocumentElement.InnerXml);
  226. // Node that isn't part of the document but created by the document.
  227. element = document.CreateElement ("foo");
  228. comment = document.CreateComment ("bar");
  229. element.AppendChild (comment);
  230. AssertEquals ("<!--bar-->", element.InnerXml);
  231. comment.Value = "baz";
  232. Assert (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo"));
  233. AssertEquals ("<!--baz-->", element.InnerXml);
  234. /*
  235. TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented.
  236. // Node that is part of the document.
  237. element = document.CreateElement ("foo");
  238. element.InnerText = "bar";
  239. document.AppendChild(element);
  240. element.InnerText = "baz";
  241. Assert(eventStrings.Contains("NodeChanged, Change, baz, foo, foo"));
  242. // Node that isn't part of the document but created by the document.
  243. element = document.CreateElement("qux");
  244. element.InnerText = "quux";
  245. element.InnerText = "quuux";
  246. Assert(eventStrings.Contains("NodeChanged, Change, quuux, qux, qux"));
  247. */
  248. }
  249. [Test]
  250. public void EventNodeChanging()
  251. {
  252. XmlElement element;
  253. XmlComment comment;
  254. document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChanging);
  255. // Node that is part of the document.
  256. document.AppendChild (document.CreateElement ("foo"));
  257. comment = document.CreateComment ("bar");
  258. document.DocumentElement.AppendChild (comment);
  259. AssertEquals ("<!--bar-->", document.DocumentElement.InnerXml);
  260. comment.Value = "baz";
  261. Assert (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo"));
  262. AssertEquals ("<!--baz-->", document.DocumentElement.InnerXml);
  263. // Node that isn't part of the document but created by the document.
  264. element = document.CreateElement ("foo");
  265. comment = document.CreateComment ("bar");
  266. element.AppendChild (comment);
  267. AssertEquals ("<!--bar-->", element.InnerXml);
  268. comment.Value = "baz";
  269. Assert (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo"));
  270. AssertEquals ("<!--baz-->", element.InnerXml);
  271. // If an exception is thrown the Document returns to original state.
  272. document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException);
  273. element = document.CreateElement("foo");
  274. comment = document.CreateComment ("bar");
  275. element.AppendChild (comment);
  276. AssertEquals ("<!--bar-->", element.InnerXml);
  277. try
  278. {
  279. comment.Value = "baz";
  280. Fail("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException().");
  281. } catch (Exception) {}
  282. AssertEquals ("<!--bar-->", element.InnerXml);
  283. // Yes it's a bit anal but this tests whether the node changing event exception fires before the
  284. // ArgumentOutOfRangeException. Turns out it does so that means our implementation needs to raise
  285. // the node changing event before doing any work.
  286. try
  287. {
  288. comment.ReplaceData(-1, 0, "qux");
  289. Fail("Expected an ArgumentOutOfRangeException to be thrown.");
  290. }
  291. catch (Exception) {}
  292. /*
  293. TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented.
  294. // Node that is part of the document.
  295. element = document.CreateElement ("foo");
  296. element.InnerText = "bar";
  297. document.AppendChild(element);
  298. element.InnerText = "baz";
  299. Assert(eventStrings.Contains("NodeChanging, Change, bar, foo, foo"));
  300. // Node that isn't part of the document but created by the document.
  301. element = document.CreateElement("foo");
  302. element.InnerText = "bar";
  303. element.InnerText = "baz";
  304. Assert(eventStrings.Contains("NodeChanging, Change, bar, foo, foo"));
  305. // If an exception is thrown the Document returns to original state.
  306. document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException);
  307. element = document.CreateElement("foo");
  308. element.InnerText = "bar";
  309. try {
  310. element.InnerText = "baz";
  311. Fail("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException().");
  312. } catch (Exception) {}
  313. AssertEquals("bar", element.InnerText);
  314. */
  315. }
  316. [Test]
  317. public void EventNodeInserted()
  318. {
  319. XmlElement element;
  320. document.NodeInserted += new XmlNodeChangedEventHandler (this.EventNodeInserted);
  321. // Inserted 'foo' element to the document.
  322. element = document.CreateElement ("foo");
  323. document.AppendChild (element);
  324. Assert (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, #document"));
  325. // Append child on node in document
  326. element = document.CreateElement ("foo");
  327. document.DocumentElement.AppendChild (element);
  328. Assert (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, foo"));
  329. // Append child on node not in document but created by document
  330. element = document.CreateElement ("bar");
  331. element.AppendChild(document.CreateElement ("bar"));
  332. Assert(eventStrings.Contains("NodeInserted, Insert, <bar />, <none>, bar"));
  333. }
  334. [Test]
  335. public void EventNodeInserting()
  336. {
  337. XmlElement element;
  338. document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInserting);
  339. // Inserting 'foo' element to the document.
  340. element = document.CreateElement ("foo");
  341. document.AppendChild (element);
  342. Assert (eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, #document"));
  343. // Append child on node in document
  344. element = document.CreateElement ("foo");
  345. document.DocumentElement.AppendChild (element);
  346. Assert(eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, foo"));
  347. // Append child on node not in document but created by document
  348. element = document.CreateElement ("bar");
  349. AssertEquals (0, element.ChildNodes.Count);
  350. element.AppendChild (document.CreateElement ("bar"));
  351. Assert (eventStrings.Contains ("NodeInserting, Insert, <bar />, <none>, bar"));
  352. AssertEquals (1, element.ChildNodes.Count);
  353. // If an exception is thrown the Document returns to original state.
  354. document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInsertingException);
  355. AssertEquals (1, element.ChildNodes.Count);
  356. try
  357. {
  358. element.AppendChild (document.CreateElement("baz"));
  359. Fail ("Expected an exception to be thrown by the NodeInserting event handler method EventNodeInsertingException().");
  360. }
  361. catch (Exception) {}
  362. AssertEquals (1, element.ChildNodes.Count);
  363. }
  364. [Test]
  365. public void EventNodeRemoved()
  366. {
  367. XmlElement element;
  368. XmlElement element2;
  369. document.NodeRemoved += new XmlNodeChangedEventHandler (this.EventNodeRemoved);
  370. // Removed 'bar' element from 'foo' outside document.
  371. element = document.CreateElement ("foo");
  372. element2 = document.CreateElement ("bar");
  373. element.AppendChild (element2);
  374. AssertEquals (1, element.ChildNodes.Count);
  375. element.RemoveChild (element2);
  376. Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
  377. AssertEquals (0, element.ChildNodes.Count);
  378. /*
  379. * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented.
  380. // RemoveAll.
  381. element = document.CreateElement ("foo");
  382. element2 = document.CreateElement ("bar");
  383. element.AppendChild(element2);
  384. AssertEquals(1, element.ChildNodes.Count);
  385. element.RemoveAll();
  386. Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
  387. AssertEquals(0, element.ChildNodes.Count);
  388. */
  389. // Removed 'bar' element from 'foo' inside document.
  390. element = document.CreateElement ("foo");
  391. document.AppendChild (element);
  392. element = document.CreateElement ("bar");
  393. document.DocumentElement.AppendChild (element);
  394. AssertEquals (1, document.DocumentElement.ChildNodes.Count);
  395. document.DocumentElement.RemoveChild (element);
  396. Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
  397. AssertEquals (0, document.DocumentElement.ChildNodes.Count);
  398. }
  399. [Test]
  400. public void EventNodeRemoving()
  401. {
  402. XmlElement element;
  403. XmlElement element2;
  404. document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemoving);
  405. // Removing 'bar' element from 'foo' outside document.
  406. element = document.CreateElement ("foo");
  407. element2 = document.CreateElement ("bar");
  408. element.AppendChild (element2);
  409. AssertEquals (1, element.ChildNodes.Count);
  410. element.RemoveChild (element2);
  411. Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
  412. AssertEquals (0, element.ChildNodes.Count);
  413. /*
  414. * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented.
  415. // RemoveAll.
  416. element = document.CreateElement ("foo");
  417. element2 = document.CreateElement ("bar");
  418. element.AppendChild(element2);
  419. AssertEquals(1, element.ChildNodes.Count);
  420. element.RemoveAll();
  421. Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
  422. AssertEquals(0, element.ChildNodes.Count);
  423. */
  424. // Removing 'bar' element from 'foo' inside document.
  425. element = document.CreateElement ("foo");
  426. document.AppendChild (element);
  427. element = document.CreateElement ("bar");
  428. document.DocumentElement.AppendChild (element);
  429. AssertEquals (1, document.DocumentElement.ChildNodes.Count);
  430. document.DocumentElement.RemoveChild (element);
  431. Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
  432. AssertEquals (0, document.DocumentElement.ChildNodes.Count);
  433. // If an exception is thrown the Document returns to original state.
  434. document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemovingException);
  435. element.AppendChild (element2);
  436. AssertEquals (1, element.ChildNodes.Count);
  437. try
  438. {
  439. element.RemoveChild(element2);
  440. Fail ("Expected an exception to be thrown by the NodeRemoving event handler method EventNodeRemovingException().");
  441. }
  442. catch (Exception) {}
  443. AssertEquals (1, element.ChildNodes.Count);
  444. }
  445. [Test]
  446. public void GetElementsByTagNameNoNameSpace ()
  447. {
  448. string xml = @"<library><book><title>XML Fun</title><author>John Doe</author>
  449. <price>34.95</price></book><book><title>Bear and the Dragon</title>
  450. <author>Tom Clancy</author><price>6.95</price></book><book>
  451. <title>Bourne Identity</title><author>Robert Ludlum</author>
  452. <price>9.95</price></book><Fluffer><Nutter><book>
  453. <title>Bourne Ultimatum</title><author>Robert Ludlum</author>
  454. <price>9.95</price></book></Nutter></Fluffer></library>";
  455. MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml));
  456. document = new XmlDocument ();
  457. document.Load (memoryStream);
  458. XmlNodeList bookList = document.GetElementsByTagName ("book");
  459. AssertEquals ("GetElementsByTagName (string) returned incorrect count.", 4, bookList.Count);
  460. }
  461. [Test]
  462. public void GetElementsByTagNameUsingNameSpace ()
  463. {
  464. StringBuilder xml = new StringBuilder ();
  465. xml.Append ("<?xml version=\"1.0\" ?><library xmlns:North=\"http://www.foo.com\" ");
  466. xml.Append ("xmlns:South=\"http://www.goo.com\"><North:book type=\"non-fiction\"> ");
  467. xml.Append ("<North:title type=\"intro\">XML Fun</North:title> " );
  468. xml.Append ("<North:author>John Doe</North:author> " );
  469. xml.Append ("<North:price>34.95</North:price></North:book> " );
  470. xml.Append ("<South:book type=\"fiction\"> " );
  471. xml.Append ("<South:title>Bear and the Dragon</South:title> " );
  472. xml.Append ("<South:author>Tom Clancy</South:author> " );
  473. xml.Append ("<South:price>6.95</South:price></South:book> " );
  474. xml.Append ("<South:book type=\"fiction\"><South:title>Bourne Identity</South:title> " );
  475. xml.Append ("<South:author>Robert Ludlum</South:author> " );
  476. xml.Append ("<South:price>9.95</South:price></South:book></library>");
  477. MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ()));
  478. document = new XmlDocument ();
  479. document.Load (memoryStream);
  480. XmlNodeList bookList = document.GetElementsByTagName ("book", "http://www.goo.com");
  481. AssertEquals ("GetElementsByTagName (string, uri) returned incorrect count.", 2, bookList.Count);
  482. }
  483. [Test]
  484. public void GetElementsByTagNameNs2 ()
  485. {
  486. document.LoadXml (@"<root>
  487. <x:a xmlns:x='urn:foo' id='a'>
  488. <y:a xmlns:y='urn:foo' id='b'/>
  489. <x:a id='c' />
  490. <z id='d' />
  491. text node
  492. <?a processing instruction ?>
  493. <x:w id='e'/>
  494. </x:a>
  495. </root>");
  496. // id='b' has different prefix. Should not caught by (name),
  497. // while should caught by (name, ns).
  498. XmlNodeList nl = document.GetElementsByTagName ("x:a");
  499. AssertEquals (2, nl.Count);
  500. AssertEquals ("a", nl [0].Attributes ["id"].Value);
  501. AssertEquals ("c", nl [1].Attributes ["id"].Value);
  502. nl = document.GetElementsByTagName ("a", "urn:foo");
  503. AssertEquals (3, nl.Count);
  504. AssertEquals ("a", nl [0].Attributes ["id"].Value);
  505. AssertEquals ("b", nl [1].Attributes ["id"].Value);
  506. AssertEquals ("c", nl [2].Attributes ["id"].Value);
  507. // name wildcard
  508. nl = document.GetElementsByTagName ("*");
  509. AssertEquals (6, nl.Count);
  510. AssertEquals ("root", nl [0].Name);
  511. AssertEquals ("a", nl [1].Attributes ["id"].Value);
  512. AssertEquals ("b", nl [2].Attributes ["id"].Value);
  513. AssertEquals ("c", nl [3].Attributes ["id"].Value);
  514. AssertEquals ("d", nl [4].Attributes ["id"].Value);
  515. AssertEquals ("e", nl [5].Attributes ["id"].Value);
  516. // wildcard - local and ns
  517. nl = document.GetElementsByTagName ("*", "*");
  518. AssertEquals (6, nl.Count);
  519. AssertEquals ("root", nl [0].Name);
  520. AssertEquals ("a", nl [1].Attributes ["id"].Value);
  521. AssertEquals ("b", nl [2].Attributes ["id"].Value);
  522. AssertEquals ("c", nl [3].Attributes ["id"].Value);
  523. AssertEquals ("d", nl [4].Attributes ["id"].Value);
  524. AssertEquals ("e", nl [5].Attributes ["id"].Value);
  525. // namespace wildcard - namespace
  526. nl = document.GetElementsByTagName ("*", "urn:foo");
  527. AssertEquals (4, nl.Count);
  528. AssertEquals ("a", nl [0].Attributes ["id"].Value);
  529. AssertEquals ("b", nl [1].Attributes ["id"].Value);
  530. AssertEquals ("c", nl [2].Attributes ["id"].Value);
  531. AssertEquals ("e", nl [3].Attributes ["id"].Value);
  532. // namespace wildcard - local only. I dare say, such usage is not XML-ish!
  533. nl = document.GetElementsByTagName ("a", "*");
  534. AssertEquals (3, nl.Count);
  535. AssertEquals ("a", nl [0].Attributes ["id"].Value);
  536. AssertEquals ("b", nl [1].Attributes ["id"].Value);
  537. AssertEquals ("c", nl [2].Attributes ["id"].Value);
  538. }
  539. [Test]
  540. public void InnerAndOuterXml ()
  541. {
  542. AssertEquals (String.Empty, document.InnerXml);
  543. AssertEquals (document.InnerXml, document.OuterXml);
  544. XmlDeclaration declaration = document.CreateXmlDeclaration ("1.0", null, null);
  545. document.AppendChild (declaration);
  546. AssertEquals ("<?xml version=\"1.0\"?>", document.InnerXml);
  547. AssertEquals (document.InnerXml, document.OuterXml);
  548. XmlElement element = document.CreateElement ("foo");
  549. document.AppendChild (element);
  550. AssertEquals ("<?xml version=\"1.0\"?><foo />", document.InnerXml);
  551. AssertEquals (document.InnerXml, document.OuterXml);
  552. XmlComment comment = document.CreateComment ("bar");
  553. document.DocumentElement.AppendChild (comment);
  554. AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar--></foo>", document.InnerXml);
  555. AssertEquals (document.InnerXml, document.OuterXml);
  556. XmlText text = document.CreateTextNode ("baz");
  557. document.DocumentElement.AppendChild (text);
  558. AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar-->baz</foo>", document.InnerXml);
  559. AssertEquals (document.InnerXml, document.OuterXml);
  560. element = document.CreateElement ("quux");
  561. element.SetAttribute ("quuux", "squonk");
  562. document.DocumentElement.AppendChild (element);
  563. AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar-->baz<quux quuux=\"squonk\" /></foo>", document.InnerXml);
  564. AssertEquals (document.InnerXml, document.OuterXml);
  565. }
  566. [Test]
  567. public void LoadWithSystemIOStream ()
  568. {
  569. string xml = @"<library><book><title>XML Fun</title><author>John Doe</author>
  570. <price>34.95</price></book><book><title>Bear and the Dragon</title>
  571. <author>Tom Clancy</author><price>6.95</price></book><book>
  572. <title>Bourne Identity</title><author>Robert Ludlum</author>
  573. <price>9.95</price></book><Fluffer><Nutter><book>
  574. <title>Bourne Ultimatum</title><author>Robert Ludlum</author>
  575. <price>9.95</price></book></Nutter></Fluffer></library>";
  576. MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml));
  577. document = new XmlDocument ();
  578. document.Load (memoryStream);
  579. AssertEquals ("Not Loaded From IOStream", true, document.HasChildNodes);
  580. }
  581. [Test]
  582. public void LoadXmlReaderNamespacesFalse ()
  583. {
  584. XmlTextReader xtr = new XmlTextReader (
  585. "<root xmlns='urn:foo' />", XmlNodeType.Document, null);
  586. xtr.Namespaces = false;
  587. document.Load (xtr); // Don't complain about xmlns attribute with its namespaceURI == String.Empty.
  588. }
  589. [Test]
  590. public void LoadXmlCDATA ()
  591. {
  592. document.LoadXml ("<foo><![CDATA[bar]]></foo>");
  593. Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.CDATA);
  594. AssertEquals ("bar", document.DocumentElement.FirstChild.Value);
  595. }
  596. [Test]
  597. public void LoadXMLComment()
  598. {
  599. // XmlTextReader needs to throw this exception
  600. // try {
  601. // document.LoadXml("<!--foo-->");
  602. // Fail("XmlException should have been thrown.");
  603. // }
  604. // catch (XmlException e) {
  605. // AssertEquals("Exception message doesn't match.", "The root element is missing.", e.Message);
  606. // }
  607. document.LoadXml ("<foo><!--Comment--></foo>");
  608. Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Comment);
  609. AssertEquals ("Comment", document.DocumentElement.FirstChild.Value);
  610. document.LoadXml (@"<foo><!--bar--></foo>");
  611. AssertEquals ("Incorrect target.", "bar", ((XmlComment)document.FirstChild.FirstChild).Data);
  612. }
  613. [Test]
  614. public void LoadXmlElementSingle ()
  615. {
  616. AssertNull (document.DocumentElement);
  617. document.LoadXml ("<foo/>");
  618. AssertNotNull (document.DocumentElement);
  619. AssertSame (document.FirstChild, document.DocumentElement);
  620. AssertEquals (String.Empty, document.DocumentElement.Prefix);
  621. AssertEquals ("foo", document.DocumentElement.LocalName);
  622. AssertEquals (String.Empty, document.DocumentElement.NamespaceURI);
  623. AssertEquals ("foo", document.DocumentElement.Name);
  624. }
  625. [Test]
  626. public void LoadXmlElementWithAttributes ()
  627. {
  628. AssertNull (document.DocumentElement);
  629. document.LoadXml ("<foo bar='baz' quux='quuux' hoge='hello &amp; world' />");
  630. XmlElement documentElement = document.DocumentElement;
  631. AssertEquals ("baz", documentElement.GetAttribute ("bar"));
  632. AssertEquals ("quuux", documentElement.GetAttribute ("quux"));
  633. AssertEquals ("hello & world", documentElement.GetAttribute ("hoge"));
  634. AssertEquals ("hello & world", documentElement.Attributes ["hoge"].Value);
  635. AssertEquals (1, documentElement.GetAttributeNode ("hoge").ChildNodes.Count);
  636. }
  637. [Test]
  638. public void LoadXmlElementWithChildElement ()
  639. {
  640. document.LoadXml ("<foo><bar/></foo>");
  641. Assert (document.ChildNodes.Count == 1);
  642. Assert (document.FirstChild.ChildNodes.Count == 1);
  643. AssertEquals ("foo", document.DocumentElement.LocalName);
  644. AssertEquals ("bar", document.DocumentElement.FirstChild.LocalName);
  645. }
  646. [Test]
  647. public void LoadXmlElementWithTextNode ()
  648. {
  649. document.LoadXml ("<foo>bar</foo>");
  650. Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Text);
  651. AssertEquals ("bar", document.DocumentElement.FirstChild.Value);
  652. }
  653. [Test]
  654. public void LoadXmlExceptionClearsDocument ()
  655. {
  656. document.LoadXml ("<foo/>");
  657. Assert (document.FirstChild != null);
  658. try {
  659. document.LoadXml ("<123/>");
  660. Fail ("An XmlException should have been thrown.");
  661. } catch (XmlException) {}
  662. Assert (document.FirstChild == null);
  663. }
  664. [Test]
  665. public void LoadXmlProcessingInstruction ()
  666. {
  667. document.LoadXml (@"<?foo bar='baaz' quux='quuux'?><quuuux></quuuux>");
  668. AssertEquals ("Incorrect target.", "foo", ((XmlProcessingInstruction)document.FirstChild).Target);
  669. AssertEquals ("Incorrect data.", "bar='baaz' quux='quuux'", ((XmlProcessingInstruction)document.FirstChild).Data);
  670. }
  671. [Test]
  672. public void OuterXml ()
  673. {
  674. string xml;
  675. xml = "<root><![CDATA[foo]]></root>";
  676. document.LoadXml (xml);
  677. AssertEquals("XmlDocument with cdata OuterXml is incorrect.", xml, document.OuterXml);
  678. xml = "<root><!--foo--></root>";
  679. document.LoadXml (xml);
  680. AssertEquals("XmlDocument with comment OuterXml is incorrect.", xml, document.OuterXml);
  681. xml = "<root><?foo bar?></root>";
  682. document.LoadXml (xml);
  683. AssertEquals("XmlDocument with processing instruction OuterXml is incorrect.", xml, document.OuterXml);
  684. }
  685. [Test]
  686. public void ParentNodes ()
  687. {
  688. document.LoadXml ("<foo><bar><baz/></bar></foo>");
  689. XmlNode node = document.FirstChild.FirstChild.FirstChild;
  690. AssertEquals ("Wrong child found.", "baz", node.LocalName);
  691. AssertEquals ("Wrong parent.", "bar", node.ParentNode.LocalName);
  692. AssertEquals ("Wrong parent.", "foo", node.ParentNode.ParentNode.LocalName);
  693. AssertEquals ("Wrong parent.", "#document", node.ParentNode.ParentNode.ParentNode.LocalName);
  694. AssertNull ("Expected parent to be null.", node.ParentNode.ParentNode.ParentNode.ParentNode);
  695. }
  696. [Test]
  697. public void RemovedElementNextSibling ()
  698. {
  699. XmlNode node;
  700. XmlNode nextSibling;
  701. document.LoadXml ("<foo><child1/><child2/></foo>");
  702. node = document.DocumentElement.FirstChild;
  703. document.DocumentElement.RemoveChild (node);
  704. nextSibling = node.NextSibling;
  705. AssertNull ("Expected removed node's next sibling to be null.", nextSibling);
  706. }
  707. // ImportNode
  708. [Test]
  709. public void ImportNode ()
  710. {
  711. XmlNode n;
  712. string xlinkURI = "http://www.w3.org/1999/XLink";
  713. string xml1 = "<?xml version='1.0' encoding='utf-8' ?><foo xmlns:xlink='" + xlinkURI + "'><bar a1='v1' xlink:href='#foo'><baz><![CDATA[cdata section.\n\titem 1\n\titem 2\n]]>From here, simple text node.</baz></bar></foo>";
  714. document.LoadXml(xml1);
  715. XmlDocument newDoc = new XmlDocument();
  716. newDoc.LoadXml("<hoge><fuga /></hoge>");
  717. XmlElement bar = document.DocumentElement.FirstChild as XmlElement;
  718. // Attribute
  719. n = newDoc.ImportNode(bar.GetAttributeNode("href", xlinkURI), true);
  720. AssertEquals("#ImportNode.Attr.NS.LocalName", "href", n.LocalName);
  721. AssertEquals("#ImportNode.Attr.NS.NSURI", xlinkURI, n.NamespaceURI);
  722. AssertEquals("#ImportNode.Attr.NS.Value", "#foo", n.Value);
  723. // CDATA
  724. n = newDoc.ImportNode(bar.FirstChild.FirstChild, true);
  725. AssertEquals("#ImportNode.CDATA", "cdata section.\n\titem 1\n\titem 2\n", n.Value);
  726. // Element
  727. XmlElement e = newDoc.ImportNode(bar, true) as XmlElement;
  728. AssertEquals("#ImportNode.Element.Name", "bar", e.Name);
  729. AssertEquals("#ImportNode.Element.Attr", "#foo", e.GetAttribute("href", xlinkURI));
  730. AssertEquals("#ImportNode.Element.deep", "baz", e.FirstChild.Name);
  731. // Entity Reference:
  732. // [2002/10/14] CreateEntityReference was not implemented.
  733. // document.LoadXml("<!DOCTYPE test PUBLIC 'dummy' [<!ENTITY FOOENT 'foo'>]><root>&FOOENT;</root>");
  734. // n = newDoc.ImportNode(document.DocumentElement.FirstChild);
  735. // AssertEquals("#ImportNode.EntityReference", "FOOENT", n.Name);
  736. // AssertEquals("#ImportNode.EntityReference", "foo_", n.Value);
  737. // Processing Instruction
  738. document.LoadXml("<foo><?xml-stylesheet href='foo.xsl' ?></foo>");
  739. XmlProcessingInstruction pi = (XmlProcessingInstruction)newDoc.ImportNode(document.DocumentElement.FirstChild, false);
  740. AssertEquals("#ImportNode.ProcessingInstruction.Name", "xml-stylesheet", pi.Name);
  741. AssertEquals("#ImportNode.ProcessingInstruction.Data", "href='foo.xsl'", pi.Data.Trim());
  742. // Text
  743. document.LoadXml(xml1);
  744. n = newDoc.ImportNode((XmlText)bar.FirstChild.ChildNodes[1], true);
  745. AssertEquals("#ImportNode.Text", "From here, simple text node.", n.Value);
  746. // XmlDeclaration
  747. document.LoadXml(xml1);
  748. XmlDeclaration decl = (XmlDeclaration)newDoc.ImportNode(document.FirstChild, false);
  749. AssertEquals("#ImportNode.XmlDeclaration.Type", XmlNodeType.XmlDeclaration, decl.NodeType);
  750. AssertEquals("#ImportNode.XmlDeclaration.Encoding", "utf-8", decl.Encoding);
  751. }
  752. [Test]
  753. public void NameTable()
  754. {
  755. XmlDocument doc = new XmlDocument();
  756. AssertNotNull(doc.NameTable);
  757. }
  758. [Test]
  759. public void SingleEmptyRootDocument()
  760. {
  761. XmlDocument doc = new XmlDocument();
  762. doc.LoadXml("<root />");
  763. AssertNotNull(doc.DocumentElement);
  764. }
  765. [Test]
  766. public void DocumentWithDoctypeDecl ()
  767. {
  768. XmlDocument doc = new XmlDocument ();
  769. // In fact it is invalid, but it doesn't fail with MS.NET 1.0.
  770. doc.LoadXml ("<!DOCTYPE test><root />");
  771. AssertNotNull (doc.DocumentType);
  772. #if NetworkEnabled
  773. try
  774. {
  775. doc.LoadXml ("<!DOCTYPE test SYSTEM 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />");
  776. } catch (XmlException) {
  777. Fail("#DoctypeDecl.System");
  778. }
  779. try {
  780. doc.LoadXml ("<!DOCTYPE test PUBLIC '-//test' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />");
  781. } catch (XmlException) {
  782. Fail ("#DoctypeDecl.Public");
  783. }
  784. #endif
  785. // Should this be commented out?
  786. doc.LoadXml ("<!DOCTYPE test [<!ELEMENT foo EMPTY>]><test><foo/></test>");
  787. }
  788. [Test]
  789. public void CloneNode ()
  790. {
  791. XmlDocument doc = new XmlDocument ();
  792. doc.LoadXml ("<foo><bar /><baz hoge='fuga'>TEST Text</baz></foo>");
  793. XmlDocument doc2 = (XmlDocument)doc.CloneNode (false);
  794. AssertEquals ("ShallowCopy", 0, doc2.ChildNodes.Count);
  795. doc2 = (XmlDocument)doc.CloneNode (true);
  796. AssertEquals ("DeepCopy", "foo", doc2.DocumentElement.Name);
  797. }
  798. [Test]
  799. public void OuterXmlWithDefaultXmlns ()
  800. {
  801. XmlDocument doc = new XmlDocument ();
  802. doc.LoadXml ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>");
  803. AssertEquals ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>", doc.OuterXml);
  804. }
  805. [Test]
  806. public void PreserveWhitespace ()
  807. {
  808. string input =
  809. "<?xml version=\"1.0\" encoding=\"utf-8\" ?><!-- --> <foo/>";
  810. XmlDocument dom = new XmlDocument ();
  811. XmlTextReader reader = new XmlTextReader (new StringReader (input));
  812. dom.Load (reader);
  813. AssertEquals (XmlNodeType.Element, dom.FirstChild.NextSibling.NextSibling.NodeType);
  814. }
  815. [Test]
  816. public void CreateAttribute ()
  817. {
  818. XmlDocument dom = new XmlDocument ();
  819. // Check that null prefix and namespace are allowed and
  820. // equivalent to ""
  821. XmlAttribute attr = dom.CreateAttribute (null, "FOO", null);
  822. AssertEquals (attr.Prefix, "");
  823. AssertEquals (attr.NamespaceURI, "");
  824. }
  825. [Test]
  826. public void DocumentTypeNodes ()
  827. {
  828. string entities = "<!ENTITY foo 'foo-ent'>";
  829. string dtd = "<!DOCTYPE root [<!ELEMENT root (#PCDATA)*> " + entities + "]>";
  830. string xml = dtd + "<root>&foo;</root>";
  831. XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null);
  832. document.Load (xvr);
  833. AssertNotNull (document.DocumentType);
  834. AssertEquals (1, document.DocumentType.Entities.Count);
  835. XmlEntity foo = document.DocumentType.Entities.GetNamedItem ("foo") as XmlEntity;
  836. AssertNotNull (foo);
  837. AssertNotNull (document.DocumentType.Entities.GetNamedItem ("foo", ""));
  838. AssertEquals ("foo", foo.Name);
  839. AssertNull (foo.Value);
  840. AssertEquals ("foo-ent", foo.InnerText);
  841. }
  842. [Test]
  843. public void DTDEntityAttributeHandling ()
  844. {
  845. string dtd = "<!DOCTYPE root[<!ATTLIST root hoge CDATA 'hoge-def'><!ENTITY foo 'ent-foo'>]>";
  846. string xml = dtd + "<root>&foo;</root>";
  847. XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document,null);
  848. xvr.EntityHandling = EntityHandling.ExpandCharEntities;
  849. xvr.ValidationType = ValidationType.None;
  850. document.Load (xvr);
  851. // Don't include default attributes here.
  852. AssertEquals (xml, document.OuterXml);
  853. AssertEquals ("hoge-def", document.DocumentElement.GetAttribute ("hoge"));
  854. }
  855. // [Test] Comment out in the meantime.
  856. // public void LoadExternalUri ()
  857. // {
  858. // // set any URL of well-formed XML.
  859. // document.Load ("http://www.go-mono.com/index.rss");
  860. // }
  861. // [Test] comment out in the meantime.
  862. // public void LoadDocumentWithIgnoreSection ()
  863. // {
  864. // // set any URL of well-formed XML.
  865. // document.Load ("xmlfiles/test.xml");
  866. // }
  867. [Test]
  868. [ExpectedException (typeof (XmlException))]
  869. public void LoadThrowsUndeclaredEntity ()
  870. {
  871. string ent1 = "<!ENTITY ent 'entity string'>";
  872. string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>";
  873. string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2;
  874. string xml = dtd + "<root>&ent3;&ent2;</root>";
  875. XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null);
  876. document.Load (xtr);
  877. xtr.Close ();
  878. }
  879. [Test]
  880. public void CreateEntityReferencesWithoutDTD ()
  881. {
  882. document.RemoveAll ();
  883. document.AppendChild (document.CreateElement ("root"));
  884. document.DocumentElement.AppendChild (document.CreateEntityReference ("foo"));
  885. }
  886. }
  887. }