2 // System.Xml.XmlDocumentTests
5 // Jason Diamond <jason@injektilo.org>
6 // Kral Ferch <kral_ferch@hotmail.com>
7 // Martin Willemoes Hansen <mwh@sysrq.dk>
9 // (C) 2002 Jason Diamond, Kral Ferch
10 // (C) 2003 Martin Willemoes Hansen
14 using System.Collections;
19 using NUnit.Framework;
21 namespace MonoTests.System.Xml
24 public class XmlDocumentTests : Assertion
26 private XmlDocument document;
27 private ArrayList eventStrings = new ArrayList();
29 // These Event* methods support the TestEventNode* Tests in this file.
30 // Most of them are event handlers for the XmlNodeChangedEventHandler
32 private void EventStringAdd(string eventName, XmlNodeChangedEventArgs e)
34 string oldParent = (e.OldParent != null) ? e.OldParent.Name : "<none>";
35 string newParent = (e.NewParent != null) ? e.NewParent.Name : "<none>";
36 eventStrings.Add (String.Format ("{0}, {1}, {2}, {3}, {4}", eventName, e.Action.ToString (), e.Node.OuterXml, oldParent, newParent));
39 private void EventNodeChanged(Object sender, XmlNodeChangedEventArgs e)
41 EventStringAdd ("NodeChanged", e);
44 private void EventNodeChanging (Object sender, XmlNodeChangedEventArgs e)
46 EventStringAdd ("NodeChanging", e);
49 private void EventNodeChangingException (Object sender, XmlNodeChangedEventArgs e)
51 throw new Exception ("don't change the value.");
54 private void EventNodeInserted(Object sender, XmlNodeChangedEventArgs e)
56 EventStringAdd ("NodeInserted", e);
59 private void EventNodeInserting(Object sender, XmlNodeChangedEventArgs e)
61 EventStringAdd ("NodeInserting", e);
64 private void EventNodeInsertingException(Object sender, XmlNodeChangedEventArgs e)
66 throw new Exception ("don't insert the element.");
69 private void EventNodeRemoved(Object sender, XmlNodeChangedEventArgs e)
71 EventStringAdd ("NodeRemoved", e);
74 private void EventNodeRemoving(Object sender, XmlNodeChangedEventArgs e)
76 EventStringAdd ("NodeRemoving", e);
79 private void EventNodeRemovingException(Object sender, XmlNodeChangedEventArgs e)
81 throw new Exception ("don't remove the element.");
85 public void GetReady ()
87 document = new XmlDocument ();
88 document.PreserveWhitespace = true;
92 public void CreateNodeNodeTypeNameEmptyParams ()
97 node = document.CreateNode (null, null, null);
98 Fail ("Expected an ArgumentException to be thrown.");
99 } catch (ArgumentException) {}
102 node = document.CreateNode ("attribute", null, null);
103 Fail ("Expected a NullReferenceException to be thrown.");
104 } catch (NullReferenceException) {}
107 node = document.CreateNode ("attribute", "", null);
108 Fail ("Expected an ArgumentException to be thrown.");
109 } catch (ArgumentException) {}
112 node = document.CreateNode ("element", null, null);
113 Fail ("Expected a NullReferenceException to be thrown.");
114 } catch (NullReferenceException) {}
117 node = document.CreateNode ("element", "", null);
118 Fail ("Expected an ArgumentException to be thrown.");
119 } catch (ArgumentException) {}
122 node = document.CreateNode ("entityreference", null, null);
123 Fail ("Expected a NullReferenceException to be thrown.");
124 } catch (NullReferenceException) {}
128 public void CreateNodeInvalidXmlNodeType ()
133 node = document.CreateNode (XmlNodeType.EndElement, null, null);
134 Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
135 } catch (ArgumentOutOfRangeException) {}
138 node = document.CreateNode (XmlNodeType.EndEntity, null, null);
139 Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
140 } catch (ArgumentOutOfRangeException) {}
143 node = document.CreateNode (XmlNodeType.Entity, null, null);
144 Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
145 } catch (ArgumentOutOfRangeException) {}
148 node = document.CreateNode (XmlNodeType.None, null, null);
149 Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
150 } catch (ArgumentOutOfRangeException) {}
153 node = document.CreateNode (XmlNodeType.Notation, null, null);
154 Fail ("Expected an ArgumentOutOfRangeException to be thrown.");
155 } catch (ArgumentOutOfRangeException) {}
157 // TODO: undocumented allowable type.
158 node = document.CreateNode (XmlNodeType.XmlDeclaration, null, null);
159 AssertEquals (XmlNodeType.XmlDeclaration, node.NodeType);
163 public void CreateNodeWhichParamIsUsed ()
167 // No constructor params for Document, DocumentFragment.
169 node = document.CreateNode (XmlNodeType.CDATA, "a", "b", "c");
170 AssertEquals (String.Empty, ((XmlCDataSection)node).Value);
172 node = document.CreateNode (XmlNodeType.Comment, "a", "b", "c");
173 AssertEquals (String.Empty, ((XmlComment)node).Value);
175 node = document.CreateNode (XmlNodeType.DocumentType, "a", "b", "c");
176 AssertNull (((XmlDocumentType)node).Value);
178 // TODO: add this back in to test when it's implemented.
179 // node = document.CreateNode (XmlNodeType.EntityReference, "a", "b", "c");
180 // AssertNull (((XmlEntityReference)node).Value);
182 node = document.CreateNode (XmlNodeType.ProcessingInstruction, "a", "b", "c");
183 AssertEquals (String.Empty, ((XmlProcessingInstruction)node).Value);
185 node = document.CreateNode (XmlNodeType.SignificantWhitespace, "a", "b", "c");
186 AssertEquals (String.Empty, ((XmlSignificantWhitespace)node).Value);
188 node = document.CreateNode (XmlNodeType.Text, "a", "b", "c");
189 AssertEquals (String.Empty, ((XmlText)node).Value);
191 node = document.CreateNode (XmlNodeType.Whitespace, "a", "b", "c");
192 AssertEquals (String.Empty, ((XmlWhitespace)node).Value);
194 node = document.CreateNode (XmlNodeType.XmlDeclaration, "a", "b", "c");
195 AssertEquals ("version=\"1.0\"", ((XmlDeclaration)node).Value);
199 public void CreateNodeNodeTypeName ()
204 node = document.CreateNode ("foo", null, null);
205 Fail ("Expected an ArgumentException to be thrown.");
206 } catch (ArgumentException) {}
208 node = document.CreateNode("attribute", "foo", null);
209 AssertEquals (XmlNodeType.Attribute, node.NodeType);
211 node = document.CreateNode("cdatasection", null, null);
212 AssertEquals (XmlNodeType.CDATA, node.NodeType);
214 node = document.CreateNode("comment", null, null);
215 AssertEquals (XmlNodeType.Comment, node.NodeType);
217 node = document.CreateNode("document", null, null);
218 AssertEquals (XmlNodeType.Document, node.NodeType);
219 // TODO: test which constructor this ended up calling,
220 // i.e. reuse underlying NameTable or not?
222 // TODO: add this back in to test when it's implemented.
223 // node = document.CreateNode("documentfragment", null, null);
224 // AssertEquals (XmlNodeType.DocumentFragment, node.NodeType);
226 node = document.CreateNode("documenttype", null, null);
227 AssertEquals (XmlNodeType.DocumentType, node.NodeType);
229 node = document.CreateNode("element", "foo", null);
230 AssertEquals (XmlNodeType.Element, node.NodeType);
232 // TODO: add this back in to test when it's implemented.
233 // node = document.CreateNode("entityreference", "foo", null);
234 // AssertEquals (XmlNodeType.EntityReference, node.NodeType);
236 node = document.CreateNode("processinginstruction", null, null);
237 AssertEquals (XmlNodeType.ProcessingInstruction, node.NodeType);
239 node = document.CreateNode("significantwhitespace", null, null);
240 AssertEquals (XmlNodeType.SignificantWhitespace, node.NodeType);
242 node = document.CreateNode("text", null, null);
243 AssertEquals (XmlNodeType.Text, node.NodeType);
245 node = document.CreateNode("whitespace", null, null);
246 AssertEquals (XmlNodeType.Whitespace, node.NodeType);
250 public void DocumentElement ()
252 AssertNull (document.DocumentElement);
253 XmlElement element = document.CreateElement ("foo", "bar", "http://foo/");
254 AssertNotNull (element);
256 AssertEquals ("foo", element.Prefix);
257 AssertEquals ("bar", element.LocalName);
258 AssertEquals ("http://foo/", element.NamespaceURI);
260 AssertEquals ("foo:bar", element.Name);
262 AssertSame (element, document.AppendChild (element));
264 AssertSame (element, document.DocumentElement);
268 public void DocumentEmpty()
270 AssertEquals ("Incorrect output for empty document.", "", document.OuterXml);
274 public void EventNodeChanged()
279 document.NodeChanged += new XmlNodeChangedEventHandler (this.EventNodeChanged);
281 // Node that is part of the document.
282 document.AppendChild (document.CreateElement ("foo"));
283 comment = document.CreateComment ("bar");
284 document.DocumentElement.AppendChild (comment);
285 AssertEquals ("<!--bar-->", document.DocumentElement.InnerXml);
286 comment.Value = "baz";
287 Assert (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo"));
288 AssertEquals ("<!--baz-->", document.DocumentElement.InnerXml);
290 // Node that isn't part of the document but created by the document.
291 element = document.CreateElement ("foo");
292 comment = document.CreateComment ("bar");
293 element.AppendChild (comment);
294 AssertEquals ("<!--bar-->", element.InnerXml);
295 comment.Value = "baz";
296 Assert (eventStrings.Contains ("NodeChanged, Change, <!--baz-->, foo, foo"));
297 AssertEquals ("<!--baz-->", element.InnerXml);
300 TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented.
302 // Node that is part of the document.
303 element = document.CreateElement ("foo");
304 element.InnerText = "bar";
305 document.AppendChild(element);
306 element.InnerText = "baz";
307 Assert(eventStrings.Contains("NodeChanged, Change, baz, foo, foo"));
309 // Node that isn't part of the document but created by the document.
310 element = document.CreateElement("qux");
311 element.InnerText = "quux";
312 element.InnerText = "quuux";
313 Assert(eventStrings.Contains("NodeChanged, Change, quuux, qux, qux"));
318 public void EventNodeChanging()
323 document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChanging);
325 // Node that is part of the document.
326 document.AppendChild (document.CreateElement ("foo"));
327 comment = document.CreateComment ("bar");
328 document.DocumentElement.AppendChild (comment);
329 AssertEquals ("<!--bar-->", document.DocumentElement.InnerXml);
330 comment.Value = "baz";
331 Assert (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo"));
332 AssertEquals ("<!--baz-->", document.DocumentElement.InnerXml);
334 // Node that isn't part of the document but created by the document.
335 element = document.CreateElement ("foo");
336 comment = document.CreateComment ("bar");
337 element.AppendChild (comment);
338 AssertEquals ("<!--bar-->", element.InnerXml);
339 comment.Value = "baz";
340 Assert (eventStrings.Contains ("NodeChanging, Change, <!--bar-->, foo, foo"));
341 AssertEquals ("<!--baz-->", element.InnerXml);
343 // If an exception is thrown the Document returns to original state.
344 document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException);
345 element = document.CreateElement("foo");
346 comment = document.CreateComment ("bar");
347 element.AppendChild (comment);
348 AssertEquals ("<!--bar-->", element.InnerXml);
351 comment.Value = "baz";
352 Fail("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException().");
353 } catch (Exception) {}
354 AssertEquals ("<!--bar-->", element.InnerXml);
356 // Yes it's a bit anal but this tests whether the node changing event exception fires before the
357 // ArgumentOutOfRangeException. Turns out it does so that means our implementation needs to raise
358 // the node changing event before doing any work.
361 comment.ReplaceData(-1, 0, "qux");
362 Fail("Expected an ArgumentOutOfRangeException to be thrown.");
367 TODO: Insert this when XmlNode.InnerText() and XmlNode.InnerXml() have been implemented.
369 // Node that is part of the document.
370 element = document.CreateElement ("foo");
371 element.InnerText = "bar";
372 document.AppendChild(element);
373 element.InnerText = "baz";
374 Assert(eventStrings.Contains("NodeChanging, Change, bar, foo, foo"));
376 // Node that isn't part of the document but created by the document.
377 element = document.CreateElement("foo");
378 element.InnerText = "bar";
379 element.InnerText = "baz";
380 Assert(eventStrings.Contains("NodeChanging, Change, bar, foo, foo"));
382 // If an exception is thrown the Document returns to original state.
383 document.NodeChanging += new XmlNodeChangedEventHandler (this.EventNodeChangingException);
384 element = document.CreateElement("foo");
385 element.InnerText = "bar";
387 element.InnerText = "baz";
388 Fail("Expected an exception to be thrown by the NodeChanging event handler method EventNodeChangingException().");
389 } catch (Exception) {}
390 AssertEquals("bar", element.InnerText);
395 public void EventNodeInserted()
399 document.NodeInserted += new XmlNodeChangedEventHandler (this.EventNodeInserted);
401 // Inserted 'foo' element to the document.
402 element = document.CreateElement ("foo");
403 document.AppendChild (element);
404 Assert (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, #document"));
406 // Append child on node in document
407 element = document.CreateElement ("foo");
408 document.DocumentElement.AppendChild (element);
409 Assert (eventStrings.Contains ("NodeInserted, Insert, <foo />, <none>, foo"));
411 // Append child on node not in document but created by document
412 element = document.CreateElement ("bar");
413 element.AppendChild(document.CreateElement ("bar"));
414 Assert(eventStrings.Contains("NodeInserted, Insert, <bar />, <none>, bar"));
418 public void EventNodeInserting()
422 document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInserting);
424 // Inserting 'foo' element to the document.
425 element = document.CreateElement ("foo");
426 document.AppendChild (element);
427 Assert (eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, #document"));
429 // Append child on node in document
430 element = document.CreateElement ("foo");
431 document.DocumentElement.AppendChild (element);
432 Assert(eventStrings.Contains ("NodeInserting, Insert, <foo />, <none>, foo"));
434 // Append child on node not in document but created by document
435 element = document.CreateElement ("bar");
436 AssertEquals (0, element.ChildNodes.Count);
437 element.AppendChild (document.CreateElement ("bar"));
438 Assert (eventStrings.Contains ("NodeInserting, Insert, <bar />, <none>, bar"));
439 AssertEquals (1, element.ChildNodes.Count);
441 // If an exception is thrown the Document returns to original state.
442 document.NodeInserting += new XmlNodeChangedEventHandler (this.EventNodeInsertingException);
443 AssertEquals (1, element.ChildNodes.Count);
446 element.AppendChild (document.CreateElement("baz"));
447 Fail ("Expected an exception to be thrown by the NodeInserting event handler method EventNodeInsertingException().");
450 AssertEquals (1, element.ChildNodes.Count);
454 public void EventNodeRemoved()
459 document.NodeRemoved += new XmlNodeChangedEventHandler (this.EventNodeRemoved);
461 // Removed 'bar' element from 'foo' outside document.
462 element = document.CreateElement ("foo");
463 element2 = document.CreateElement ("bar");
464 element.AppendChild (element2);
465 AssertEquals (1, element.ChildNodes.Count);
466 element.RemoveChild (element2);
467 Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
468 AssertEquals (0, element.ChildNodes.Count);
471 * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented.
474 element = document.CreateElement ("foo");
475 element2 = document.CreateElement ("bar");
476 element.AppendChild(element2);
477 AssertEquals(1, element.ChildNodes.Count);
479 Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
480 AssertEquals(0, element.ChildNodes.Count);
483 // Removed 'bar' element from 'foo' inside document.
484 element = document.CreateElement ("foo");
485 document.AppendChild (element);
486 element = document.CreateElement ("bar");
487 document.DocumentElement.AppendChild (element);
488 AssertEquals (1, document.DocumentElement.ChildNodes.Count);
489 document.DocumentElement.RemoveChild (element);
490 Assert (eventStrings.Contains ("NodeRemoved, Remove, <bar />, foo, <none>"));
491 AssertEquals (0, document.DocumentElement.ChildNodes.Count);
495 public void EventNodeRemoving()
500 document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemoving);
502 // Removing 'bar' element from 'foo' outside document.
503 element = document.CreateElement ("foo");
504 element2 = document.CreateElement ("bar");
505 element.AppendChild (element2);
506 AssertEquals (1, element.ChildNodes.Count);
507 element.RemoveChild (element2);
508 Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
509 AssertEquals (0, element.ChildNodes.Count);
512 * TODO: put this test back in when AttributeCollection.RemoveAll() is implemented.
515 element = document.CreateElement ("foo");
516 element2 = document.CreateElement ("bar");
517 element.AppendChild(element2);
518 AssertEquals(1, element.ChildNodes.Count);
520 Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
521 AssertEquals(0, element.ChildNodes.Count);
524 // Removing 'bar' element from 'foo' inside document.
525 element = document.CreateElement ("foo");
526 document.AppendChild (element);
527 element = document.CreateElement ("bar");
528 document.DocumentElement.AppendChild (element);
529 AssertEquals (1, document.DocumentElement.ChildNodes.Count);
530 document.DocumentElement.RemoveChild (element);
531 Assert (eventStrings.Contains ("NodeRemoving, Remove, <bar />, foo, <none>"));
532 AssertEquals (0, document.DocumentElement.ChildNodes.Count);
534 // If an exception is thrown the Document returns to original state.
535 document.NodeRemoving += new XmlNodeChangedEventHandler (this.EventNodeRemovingException);
536 element.AppendChild (element2);
537 AssertEquals (1, element.ChildNodes.Count);
540 element.RemoveChild(element2);
541 Fail ("Expected an exception to be thrown by the NodeRemoving event handler method EventNodeRemovingException().");
544 AssertEquals (1, element.ChildNodes.Count);
548 public void GetElementsByTagNameNoNameSpace ()
550 string xml = @"<library><book><title>XML Fun</title><author>John Doe</author>
551 <price>34.95</price></book><book><title>Bear and the Dragon</title>
552 <author>Tom Clancy</author><price>6.95</price></book><book>
553 <title>Bourne Identity</title><author>Robert Ludlum</author>
554 <price>9.95</price></book><Fluffer><Nutter><book>
555 <title>Bourne Ultimatum</title><author>Robert Ludlum</author>
556 <price>9.95</price></book></Nutter></Fluffer></library>";
558 MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml));
559 document = new XmlDocument ();
560 document.Load (memoryStream);
561 XmlNodeList bookList = document.GetElementsByTagName ("book");
562 AssertEquals ("GetElementsByTagName (string) returned incorrect count.", 4, bookList.Count);
566 public void GetElementsByTagNameUsingNameSpace ()
568 StringBuilder xml = new StringBuilder ();
569 xml.Append ("<?xml version=\"1.0\" ?><library xmlns:North=\"http://www.foo.com\" ");
570 xml.Append ("xmlns:South=\"http://www.goo.com\"><North:book type=\"non-fiction\"> ");
571 xml.Append ("<North:title type=\"intro\">XML Fun</North:title> " );
572 xml.Append ("<North:author>John Doe</North:author> " );
573 xml.Append ("<North:price>34.95</North:price></North:book> " );
574 xml.Append ("<South:book type=\"fiction\"> " );
575 xml.Append ("<South:title>Bear and the Dragon</South:title> " );
576 xml.Append ("<South:author>Tom Clancy</South:author> " );
577 xml.Append ("<South:price>6.95</South:price></South:book> " );
578 xml.Append ("<South:book type=\"fiction\"><South:title>Bourne Identity</South:title> " );
579 xml.Append ("<South:author>Robert Ludlum</South:author> " );
580 xml.Append ("<South:price>9.95</South:price></South:book></library>");
582 MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml.ToString ()));
583 document = new XmlDocument ();
584 document.Load (memoryStream);
585 XmlNodeList bookList = document.GetElementsByTagName ("book", "http://www.goo.com");
586 AssertEquals ("GetElementsByTagName (string, uri) returned incorrect count.", 2, bookList.Count);
590 public void GetElementsByTagNameNs2 ()
592 document.LoadXml (@"<root>
\r
593 <x:a xmlns:x='urn:foo' id='a'>
\r
594 <y:a xmlns:y='urn:foo' id='b'/>
\r
598 <?a processing instruction ?>
\r
602 // id='b' has different prefix. Should not caught by (name),
\r
603 // while should caught by (name, ns).
\r
604 XmlNodeList nl = document.GetElementsByTagName ("x:a");
\r
605 AssertEquals (2, nl.Count);
\r
606 AssertEquals ("a", nl [0].Attributes ["id"].Value);
\r
607 AssertEquals ("c", nl [1].Attributes ["id"].Value);
\r
609 nl = document.GetElementsByTagName ("a", "urn:foo");
\r
610 AssertEquals (3, nl.Count);
\r
611 AssertEquals ("a", nl [0].Attributes ["id"].Value);
\r
612 AssertEquals ("b", nl [1].Attributes ["id"].Value);
\r
613 AssertEquals ("c", nl [2].Attributes ["id"].Value);
\r
616 nl = document.GetElementsByTagName ("*");
\r
617 AssertEquals (6, nl.Count);
\r
618 AssertEquals ("root", nl [0].Name);
\r
619 AssertEquals ("a", nl [1].Attributes ["id"].Value);
\r
620 AssertEquals ("b", nl [2].Attributes ["id"].Value);
\r
621 AssertEquals ("c", nl [3].Attributes ["id"].Value);
\r
622 AssertEquals ("d", nl [4].Attributes ["id"].Value);
\r
623 AssertEquals ("e", nl [5].Attributes ["id"].Value);
\r
625 // wildcard - local and ns
626 nl = document.GetElementsByTagName ("*", "*");
\r
627 AssertEquals (6, nl.Count);
\r
628 AssertEquals ("root", nl [0].Name);
\r
629 AssertEquals ("a", nl [1].Attributes ["id"].Value);
\r
630 AssertEquals ("b", nl [2].Attributes ["id"].Value);
\r
631 AssertEquals ("c", nl [3].Attributes ["id"].Value);
\r
632 AssertEquals ("d", nl [4].Attributes ["id"].Value);
\r
633 AssertEquals ("e", nl [5].Attributes ["id"].Value);
\r
635 // namespace wildcard - namespace
636 nl = document.GetElementsByTagName ("*", "urn:foo");
\r
637 AssertEquals (4, nl.Count);
\r
638 AssertEquals ("a", nl [0].Attributes ["id"].Value);
\r
639 AssertEquals ("b", nl [1].Attributes ["id"].Value);
\r
640 AssertEquals ("c", nl [2].Attributes ["id"].Value);
\r
641 AssertEquals ("e", nl [3].Attributes ["id"].Value);
\r
643 // namespace wildcard - local only. I dare say, such usage is not XML-ish!
644 nl = document.GetElementsByTagName ("a", "*");
\r
645 AssertEquals (3, nl.Count);
\r
646 AssertEquals ("a", nl [0].Attributes ["id"].Value);
\r
647 AssertEquals ("b", nl [1].Attributes ["id"].Value);
\r
648 AssertEquals ("c", nl [2].Attributes ["id"].Value);
\r
652 public void Implementation ()
654 AssertNotNull (new XmlDocument ().Implementation);
658 public void InnerAndOuterXml ()
660 AssertEquals (String.Empty, document.InnerXml);
661 AssertEquals (document.InnerXml, document.OuterXml);
663 XmlDeclaration declaration = document.CreateXmlDeclaration ("1.0", null, null);
664 document.AppendChild (declaration);
665 AssertEquals ("<?xml version=\"1.0\"?>", document.InnerXml);
666 AssertEquals (document.InnerXml, document.OuterXml);
668 XmlElement element = document.CreateElement ("foo");
669 document.AppendChild (element);
670 AssertEquals ("<?xml version=\"1.0\"?><foo />", document.InnerXml);
671 AssertEquals (document.InnerXml, document.OuterXml);
673 XmlComment comment = document.CreateComment ("bar");
674 document.DocumentElement.AppendChild (comment);
675 AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar--></foo>", document.InnerXml);
676 AssertEquals (document.InnerXml, document.OuterXml);
678 XmlText text = document.CreateTextNode ("baz");
679 document.DocumentElement.AppendChild (text);
680 AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar-->baz</foo>", document.InnerXml);
681 AssertEquals (document.InnerXml, document.OuterXml);
683 element = document.CreateElement ("quux");
684 element.SetAttribute ("quuux", "squonk");
685 document.DocumentElement.AppendChild (element);
686 AssertEquals ("<?xml version=\"1.0\"?><foo><!--bar-->baz<quux quuux=\"squonk\" /></foo>", document.InnerXml);
687 AssertEquals (document.InnerXml, document.OuterXml);
691 public void LoadWithSystemIOStream ()
693 string xml = @"<library><book><title>XML Fun</title><author>John Doe</author>
694 <price>34.95</price></book><book><title>Bear and the Dragon</title>
695 <author>Tom Clancy</author><price>6.95</price></book><book>
696 <title>Bourne Identity</title><author>Robert Ludlum</author>
697 <price>9.95</price></book><Fluffer><Nutter><book>
698 <title>Bourne Ultimatum</title><author>Robert Ludlum</author>
699 <price>9.95</price></book></Nutter></Fluffer></library>";
701 MemoryStream memoryStream = new MemoryStream (Encoding.UTF8.GetBytes (xml));
702 document = new XmlDocument ();
703 document.Load (memoryStream);
704 AssertEquals ("Not Loaded From IOStream", true, document.HasChildNodes);
708 public void LoadXmlReaderNamespacesFalse ()
710 XmlTextReader xtr = new XmlTextReader (
711 "<root xmlns='urn:foo' />", XmlNodeType.Document, null);
712 xtr.Namespaces = false;
713 document.Load (xtr); // Don't complain about xmlns attribute with its namespaceURI == String.Empty.
717 public void LoadXmlCDATA ()
719 document.LoadXml ("<foo><![CDATA[bar]]></foo>");
720 Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.CDATA);
721 AssertEquals ("bar", document.DocumentElement.FirstChild.Value);
725 public void LoadXMLComment()
727 // XmlTextReader needs to throw this exception
729 // document.LoadXml("<!--foo-->");
730 // Fail("XmlException should have been thrown.");
732 // catch (XmlException e) {
733 // AssertEquals("Exception message doesn't match.", "The root element is missing.", e.Message);
736 document.LoadXml ("<foo><!--Comment--></foo>");
737 Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Comment);
738 AssertEquals ("Comment", document.DocumentElement.FirstChild.Value);
740 document.LoadXml (@"<foo><!--bar--></foo>");
741 AssertEquals ("Incorrect target.", "bar", ((XmlComment)document.FirstChild.FirstChild).Data);
745 public void LoadXmlElementSingle ()
747 AssertNull (document.DocumentElement);
748 document.LoadXml ("<foo/>");
750 AssertNotNull (document.DocumentElement);
751 AssertSame (document.FirstChild, document.DocumentElement);
753 AssertEquals (String.Empty, document.DocumentElement.Prefix);
754 AssertEquals ("foo", document.DocumentElement.LocalName);
755 AssertEquals (String.Empty, document.DocumentElement.NamespaceURI);
756 AssertEquals ("foo", document.DocumentElement.Name);
760 public void LoadXmlElementWithAttributes ()
762 AssertNull (document.DocumentElement);
763 document.LoadXml ("<foo bar='baz' quux='quuux' hoge='hello & world' />");
765 XmlElement documentElement = document.DocumentElement;
767 AssertEquals ("baz", documentElement.GetAttribute ("bar"));
768 AssertEquals ("quuux", documentElement.GetAttribute ("quux"));
769 AssertEquals ("hello & world", documentElement.GetAttribute ("hoge"));
770 AssertEquals ("hello & world", documentElement.Attributes ["hoge"].Value);
771 AssertEquals (1, documentElement.GetAttributeNode ("hoge").ChildNodes.Count);
775 public void LoadXmlElementWithChildElement ()
777 document.LoadXml ("<foo><bar/></foo>");
778 Assert (document.ChildNodes.Count == 1);
779 Assert (document.FirstChild.ChildNodes.Count == 1);
780 AssertEquals ("foo", document.DocumentElement.LocalName);
781 AssertEquals ("bar", document.DocumentElement.FirstChild.LocalName);
785 public void LoadXmlElementWithTextNode ()
787 document.LoadXml ("<foo>bar</foo>");
788 Assert (document.DocumentElement.FirstChild.NodeType == XmlNodeType.Text);
789 AssertEquals ("bar", document.DocumentElement.FirstChild.Value);
793 public void LoadXmlExceptionClearsDocument ()
795 document.LoadXml ("<foo/>");
796 Assert (document.FirstChild != null);
799 document.LoadXml ("<123/>");
800 Fail ("An XmlException should have been thrown.");
801 } catch (XmlException) {}
803 Assert (document.FirstChild == null);
807 public void LoadXmlProcessingInstruction ()
809 document.LoadXml (@"<?foo bar='baaz' quux='quuux'?><quuuux></quuuux>");
810 AssertEquals ("Incorrect target.", "foo", ((XmlProcessingInstruction)document.FirstChild).Target);
811 AssertEquals ("Incorrect data.", "bar='baaz' quux='quuux'", ((XmlProcessingInstruction)document.FirstChild).Data);
815 public void OuterXml ()
819 xml = "<root><![CDATA[foo]]></root>";
820 document.LoadXml (xml);
821 AssertEquals("XmlDocument with cdata OuterXml is incorrect.", xml, document.OuterXml);
823 xml = "<root><!--foo--></root>";
824 document.LoadXml (xml);
825 AssertEquals("XmlDocument with comment OuterXml is incorrect.", xml, document.OuterXml);
827 xml = "<root><?foo bar?></root>";
828 document.LoadXml (xml);
829 AssertEquals("XmlDocument with processing instruction OuterXml is incorrect.", xml, document.OuterXml);
833 public void ParentNodes ()
835 document.LoadXml ("<foo><bar><baz/></bar></foo>");
836 XmlNode node = document.FirstChild.FirstChild.FirstChild;
837 AssertEquals ("Wrong child found.", "baz", node.LocalName);
838 AssertEquals ("Wrong parent.", "bar", node.ParentNode.LocalName);
839 AssertEquals ("Wrong parent.", "foo", node.ParentNode.ParentNode.LocalName);
840 AssertEquals ("Wrong parent.", "#document", node.ParentNode.ParentNode.ParentNode.LocalName);
841 AssertNull ("Expected parent to be null.", node.ParentNode.ParentNode.ParentNode.ParentNode);
845 public void RemovedElementNextSibling ()
850 document.LoadXml ("<foo><child1/><child2/></foo>");
851 node = document.DocumentElement.FirstChild;
852 document.DocumentElement.RemoveChild (node);
853 nextSibling = node.NextSibling;
854 AssertNull ("Expected removed node's next sibling to be null.", nextSibling);
859 public void ImportNode ()
863 string xlinkURI = "http://www.w3.org/1999/XLink";
864 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>";
865 document.LoadXml(xml1);
866 XmlDocument newDoc = new XmlDocument();
867 newDoc.LoadXml("<hoge><fuga /></hoge>");
868 XmlElement bar = document.DocumentElement.FirstChild as XmlElement;
871 n = newDoc.ImportNode(bar.GetAttributeNode("href", xlinkURI), true);
872 AssertEquals("#ImportNode.Attr.NS.LocalName", "href", n.LocalName);
873 AssertEquals("#ImportNode.Attr.NS.NSURI", xlinkURI, n.NamespaceURI);
874 AssertEquals("#ImportNode.Attr.NS.Value", "#foo", n.Value);
877 n = newDoc.ImportNode(bar.FirstChild.FirstChild, true);
878 AssertEquals("#ImportNode.CDATA", "cdata section.\n\titem 1\n\titem 2\n", n.Value);
881 XmlElement e = newDoc.ImportNode(bar, true) as XmlElement;
882 AssertEquals("#ImportNode.Element.Name", "bar", e.Name);
883 AssertEquals("#ImportNode.Element.Attr", "#foo", e.GetAttribute("href", xlinkURI));
884 AssertEquals("#ImportNode.Element.deep", "baz", e.FirstChild.Name);
887 // [2002/10/14] CreateEntityReference was not implemented.
888 // document.LoadXml("<!DOCTYPE test PUBLIC 'dummy' [<!ENTITY FOOENT 'foo'>]><root>&FOOENT;</root>");
889 // n = newDoc.ImportNode(document.DocumentElement.FirstChild);
890 // AssertEquals("#ImportNode.EntityReference", "FOOENT", n.Name);
891 // AssertEquals("#ImportNode.EntityReference", "foo_", n.Value);
893 // Processing Instruction
894 document.LoadXml("<foo><?xml-stylesheet href='foo.xsl' ?></foo>");
895 XmlProcessingInstruction pi = (XmlProcessingInstruction)newDoc.ImportNode(document.DocumentElement.FirstChild, false);
896 AssertEquals("#ImportNode.ProcessingInstruction.Name", "xml-stylesheet", pi.Name);
897 AssertEquals("#ImportNode.ProcessingInstruction.Data", "href='foo.xsl'", pi.Data.Trim());
900 document.LoadXml(xml1);
901 n = newDoc.ImportNode((XmlText)bar.FirstChild.ChildNodes[1], true);
902 AssertEquals("#ImportNode.Text", "From here, simple text node.", n.Value);
905 document.LoadXml(xml1);
906 XmlDeclaration decl = (XmlDeclaration)newDoc.ImportNode(document.FirstChild, false);
907 AssertEquals("#ImportNode.XmlDeclaration.Type", XmlNodeType.XmlDeclaration, decl.NodeType);
908 AssertEquals("#ImportNode.XmlDeclaration.Encoding", "utf-8", decl.Encoding);
912 public void NameTable()
914 XmlDocument doc = new XmlDocument();
915 AssertNotNull(doc.NameTable);
919 public void SingleEmptyRootDocument()
921 XmlDocument doc = new XmlDocument();
922 doc.LoadXml("<root />");
923 AssertNotNull(doc.DocumentElement);
927 public void DocumentWithDoctypeDecl ()
929 XmlDocument doc = new XmlDocument ();
930 // In fact it is invalid, but it doesn't fail with MS.NET 1.0.
931 doc.LoadXml ("<!DOCTYPE test><root />");
932 AssertNotNull (doc.DocumentType);
936 doc.LoadXml ("<!DOCTYPE test SYSTEM 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />");
937 } catch (XmlException) {
938 Fail("#DoctypeDecl.System");
941 doc.LoadXml ("<!DOCTYPE test PUBLIC '-//test' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><root />");
942 } catch (XmlException) {
943 Fail ("#DoctypeDecl.Public");
946 // Should this be commented out?
947 doc.LoadXml ("<!DOCTYPE test [<!ELEMENT foo EMPTY>]><test><foo/></test>");
951 public void CloneNode ()
953 XmlDocument doc = new XmlDocument ();
954 doc.LoadXml ("<foo><bar /><baz hoge='fuga'>TEST Text</baz></foo>");
955 XmlDocument doc2 = (XmlDocument)doc.CloneNode (false);
956 AssertEquals ("ShallowCopy", 0, doc2.ChildNodes.Count);
957 doc2 = (XmlDocument)doc.CloneNode (true);
958 AssertEquals ("DeepCopy", "foo", doc2.DocumentElement.Name);
962 public void OuterXmlWithDefaultXmlns ()
964 XmlDocument doc = new XmlDocument ();
965 doc.LoadXml ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>");
966 AssertEquals ("<iq type=\"get\" id=\"ATECLIENT_1\"><query xmlns=\"jabber:iq:auth\"><username></username></query></iq>", doc.OuterXml);
970 public void PreserveWhitespace ()
973 "<?xml version=\"1.0\" encoding=\"utf-8\" ?><!-- --> <foo/>";
975 XmlDocument dom = new XmlDocument ();
976 XmlTextReader reader = new XmlTextReader (new StringReader (input));
979 AssertEquals (XmlNodeType.Element, dom.FirstChild.NextSibling.NextSibling.NodeType);
983 public void PreserveWhitespace2 ()
985 XmlDocument doc = new XmlDocument ();
986 Assert (!doc.PreserveWhitespace);
987 doc.PreserveWhitespace = true;
988 XmlDocument d2 = doc.Clone () as XmlDocument;
989 Assert (!d2.PreserveWhitespace); // i.e. not cloned
990 d2.AppendChild (d2.CreateElement ("root"));
991 d2.DocumentElement.AppendChild (d2.CreateWhitespace (" "));
992 StringWriter sw = new StringWriter ();
993 d2.WriteTo (new XmlTextWriter (sw));
994 AssertEquals ("<root> </root>", sw.ToString ());
998 public void CreateAttribute ()
1000 XmlDocument dom = new XmlDocument ();
1002 // Check that null prefix and namespace are allowed and
1004 XmlAttribute attr = dom.CreateAttribute (null, "FOO", null);
1005 AssertEquals (attr.Prefix, "");
1006 AssertEquals (attr.NamespaceURI, "");
1010 public void DocumentTypeNodes ()
1012 string entities = "<!ENTITY foo 'foo-ent'>";
1013 string dtd = "<!DOCTYPE root [<!ELEMENT root (#PCDATA)*> " + entities + "]>";
1014 string xml = dtd + "<root>&foo;</root>";
1015 XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null);
1016 document.Load (xvr);
1017 AssertNotNull (document.DocumentType);
1018 AssertEquals (1, document.DocumentType.Entities.Count);
1020 XmlEntity foo = document.DocumentType.Entities.GetNamedItem ("foo") as XmlEntity;
1021 AssertNotNull (foo);
1022 AssertNotNull (document.DocumentType.Entities.GetNamedItem ("foo", ""));
1023 AssertEquals ("foo", foo.Name);
1024 AssertNull (foo.Value);
1025 AssertEquals ("foo-ent", foo.InnerText);
1029 public void DTDEntityAttributeHandling ()
1031 string dtd = "<!DOCTYPE root[<!ATTLIST root hoge CDATA 'hoge-def'><!ENTITY foo 'ent-foo'>]>";
1032 string xml = dtd + "<root>&foo;</root>";
1033 XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document,null);
1034 xvr.EntityHandling = EntityHandling.ExpandCharEntities;
1035 xvr.ValidationType = ValidationType.None;
1036 document.Load (xvr);
1037 // Don't include default attributes here.
1038 AssertEquals (xml, document.OuterXml);
1039 AssertEquals ("hoge-def", document.DocumentElement.GetAttribute ("hoge"));
1042 // [Test] Comment out in the meantime.
1043 // public void LoadExternalUri ()
1045 // // set any URL of well-formed XML.
1046 // document.Load ("http://www.go-mono.com/index.rss");
1049 // [Test] comment out in the meantime.
1050 // public void LoadDocumentWithIgnoreSection ()
1052 // // set any URL of well-formed XML.
1053 // document.Load ("xmlfiles/test.xml");
1057 [ExpectedException (typeof (XmlException))]
1058 public void LoadThrowsUndeclaredEntity ()
1060 string ent1 = "<!ENTITY ent 'entity string'>";
1061 string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>";
1062 string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2;
1063 string xml = dtd + "<root>&ent3;&ent2;</root>";
1064 XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null);
1065 document.Load (xtr);
1070 public void CreateEntityReferencesWithoutDTD ()
1072 document.RemoveAll ();
1073 document.AppendChild (document.CreateElement ("root"));
1074 document.DocumentElement.AppendChild (document.CreateEntityReference ("foo"));
1078 public void ReadNodeEmptyContent ()
1080 XmlTextReader xr = new XmlTextReader ("", XmlNodeType.Element, null);
\r
1082 Console.WriteLine (xr.NodeType);
\r
1083 XmlNode n = document.ReadNode (xr);
\r
1088 public void ReadNodeWhitespace ()
1090 XmlTextReader xr = new XmlTextReader (" ", XmlNodeType.Element, null);
\r
1092 Console.WriteLine (xr.NodeType);
\r
1093 document.PreserveWhitespace = false; // Note this line.
1094 XmlNode n = document.ReadNode (xr);
\r
1095 AssertNotNull (n);
\r
1096 AssertEquals (XmlNodeType.Whitespace, n.NodeType);
\r