I am trying to validate an XML file that does not contain any xmlns: namespace attribute against a
predefined XSD schema.
I should think this would be easy to do, since there must be far more "unqualified" XML files out
there than there are ones that include a namespace reference.
Unfortunately, as I am coming to hate about all things XML, the easy things are extraordinarily
difficult and/or subtle.
I know how to create a schema collection dynamically and validate qualified XML files against it.
But I can't figure out the "no namespace in the XML file" situation (other than rewriting the XML
file to include an xmlns: attribute at the root, but that's too ugly to think about).
I tried, among many other things:
FileStream xsdStream = File.OpenRead(schemaFile);
XmlTextReader xsdTR = new XmlTextReader(xsdStream);
XmlSchemaCollection schemaColl = new XmlSchemaCollection();
schemaColl.Add("http://tempuri.org/finance.xsd", xsdTR);
FileStream xmlStream = File.OpenRead(fileName);
XmlTextReader xmlTR = new XmlTextReader(xmlStream);
XmlValidatingReader xmlReader = new XmlValidatingReader(xmlTR);
xmlReader.ValidationType = ValidationType.Schema;
xmlReader.Schemas.Add(schemaColl);
xmlReader.ValidationEventHandler += new ValidationEventHandler(xmlReader_ValidationEventHa ndler);
XmlNamespaceManager theNSM = new XmlNamespaceManager(xmlTR.NameTable);
theNSM.AddNamespace(String.Empty, "http://tempuri.org/finance.xsd");
but that doesn't work, blowing up on the root element of the XML file, complaining that it can't
find schema information for the unqualified root element name.
So how the heck do I validate an XML file that has no namespace attributes???
- Mark