2

A colleague of mine encountered a situation where the XMLSerializer behaves differently when run via MSTest Runner or via NCrunch.

When running test through N-Crunch the output contains

xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

When run via MSTest Runner the output contains

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

The order of xsi and xsd is different. The rest of the output is the same.

What could be the cause of this?

We don't use any <system.xml.serialization> settings in the configs.

tymtam
  • 31,798
  • 8
  • 86
  • 126

2 Answers2

4

I can't answer your original question, which I found because we have exactly the same problem with MsTest and NUnit, but I can recommend an effective workaround for anyone else who finds themselves in this situation. This is using XML Canonicalization, eg:

using System.Security.Cryptography.Xml;

string canonicaliseXml(string xmlInput)
{
    XmlDocument myDoc = new XmlDocument();
    myDoc.LoadXml(xmlInput);
    XmlDsigC14NTransform t = new XmlDsigC14NTransform();
    t.LoadInput (myDoc);
    var ms = (MemoryStream)t.GetOutput();
    return Encoding.UTF8.GetString(ms.ToArray());
}

XML Canonicalization normalises XML strings by steps like removing white space between elements, ordering attributes alphabetically and expanding short-form empty elements (there's a helpful explanation at http://en.wikipedia.org/wiki/Canonical_XML) so that:

<root x='x'  a='a'>  <trunk>etc</trunk> <empty />  </root> 

will be canonicalised as

<root a="a" x="x"><trunk>etc</trunk><empty></empty></root> 

Obviously this will resolve any difference in the ordering of the xsd and xsi namespace declarations, as experienced by us and by the original poster.

EDIT If you want to take a belt-and-braces approach, you could combine this with the "new XmlSerializerNamespaces()" technique in http://silent-code.blogspot.co.uk/2009/09/using-xmlserializer-without-rendering.html, which filters the redundant xsd and xsi namespace declarations from the initial serialization.

Francis Norton
  • 674
  • 1
  • 8
  • 16
3

Assuming that NCrunch and NUnit work the same way, the reason that there is a difference is because MS Test runs the 32 bit version of XmlSerializer and NCrunch runs the 64 bit version. In order to make NCrunch work the same way as MS Test this you could specify x86 as the platform target for your NCrunch test project.

Technically the two versions of XML are exactly the same and the order shouldn't matter, therefore Francis' workaround makes sense when testing that your XML is correct.

Stephen Oberauer
  • 5,237
  • 6
  • 53
  • 75