Category Archives: XML

XML validation using XSD succeeds when the XML is invalid

Problem: I inherited a bit of code from previous developers. This loaded a XSD into the readersettings and attempted to validate a received XML document.

What I noticed however is that the XML document ALWAYS passed the XSD validation, even though it was correct. Eventually I found a post describing a possible cause of the problem. My XSD had a namespace explicitly defined. The XML I received had no namespace. For some reason because the XML is NOT in the namespace of the XSD it will always pass the validation…wierd.

Solution: Create a default namespace. The XML will automatically be defined as being part of the namespace and hence will be validated against the XSD correctly.

I copied this code from the interwebs, but can’t remember where, so sorry for the lack of credit to the original author.

Something like this

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;

settings.Schemas.Add(null, HostingEnvironment.MapPath(schemaLocation));

settings.NameTable = new NameTable();
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(settings.NameTable);
nameSpaceManager.AddNamespace(“”, “xxxNAMESPACExxx”);
XmlParserContext parserContext = new XmlParserContext(settings.NameTable, nameSpaceManager, “”, XmlSpace.Default);

XmlDocument xmlDoc = new XmlDocument();
XmlReader reader = XmlReader.Create(contentStream, settings, parserContext);
xmlDoc.Load(reader);

Advertisements

Root Element is Missing (reading XML)

Problem: While trying to read a stream containing XML twice, I kept getting the error ‘Root Element is Missing’, even though the XML was 100% correct.

After searching the net for a bit I came across an article about streams and the position in that stream (thanks Edward Weinert). After seeing this I realised that the 1st read was moving the position in the stream to the end. The 2nd read was starting from the end of the stream, and therefore finding NO root element in the XML.

Solution: The concept of the solution is simple, set the position to 0 after the stream has been read. The code was somewhat harder, but thanks to StackOverflow I found the solution. (http://stackoverflow.com/questions/147941/how-can-i-read-an-http-response-stream-twice-in-c)

Stream responseStream = CopyStream(resp.GetResponseStream());
// Do something with the stream
responseStream.Seek(0, SeekOrigin.Begin);
// Do something with the stream again

private static Stream CopyStream(Stream inputStream)
{
const int readSize = 256;
byte[] buffer = new byte[readSize];
MemoryStream ms = new MemoryStream();

int count = inputStream.Read(buffer, 0, readSize);
while (count > 0)
{
ms.Write(buffer, 0, count);
count = inputStream.Read(buffer, 0, readSize);
}
ms.Seek(0, SeekOrigin.Begin);
return ms;
}