Tuesday, January 30, 2007

troubles with XmlDocument

I love it when things don't quite work the way you think... especially when the thing that doesn't work is just totally weird...

We were writing tests today for a class that uses XmlDocuments. To test the xml loaded/saved, we used memorysteams and byte arrays to control what was loaded and validate what was saved.

Seemed simple enough and our xml was even simpler:
string someXml = "<myxmlnode someattribute="value"/>"

The following code saved the xml into a memory stream:
XmlDocument document = new XmlDocument();
document.LoadXml(someXml);
MemoryStream stream = new MemoryStream();
document.Save(stream);

A bit later this stream was loaded by our class under test
XmlDocument anotherDocument = new XmlDocument();
anotherDocument.Load(stream); <----- THIS THROWS AN EXCEPTION!!!!

We read the bytes of the stream and decoded it to reveal this text:
"<myxmlnode someattribute="value" />"

Do you see? The difference is subtle, but enough to cause a problem. It seems the xml document added a space between the quote and the closing tag and this made it impossible to load the steam.

It took us some time to narrow down this as the cause of the error and we didn't spent too much try trying to figure it out, so we just changed the xml to this:
"<myxmlnode someattribute="value"></myxmlnode>"

Problem solved... well not really, but it loaded and fixed the test -- I would assume there is a flag or something to change this behavior, but I would have thought the default behavior of save/load would work together

No comments: