Xml – The targetNamespace parameter should be the same value as the targetNamespace of the schema

xmlxml-validationxsdxsd-validation

I am getting this error when I read an xml file with inline schema validation. The XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<SysConfig xmlns="PM-NameSpace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="SysConfig.xsd">
...
</SysConfig>

The XSD file is in the same folder as the XML file and is called "SysConfig.xsd" and looks like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="PM-NameSpace" targetNamespace="PM-NameSpace">
...
</xs:schema>

I want to do inline schema validation in code, so my C# looks like this:

XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(handler);
XmlReader xmlReader = XmlReader.Create(sysConfigPath, xmlReaderSettings);
XmlDocument sysConfigXmlDocument = new XmlDocument();
sysConfigXmlDocument.Load(xmlReader);

As soon as Load is called (last line) the validation event handler is invoked, the actual message being:

Cannot load the schema for the namespace ' ' – The targetNamespace parameter ' ' should be the same value as the targetNamespace 'PM-NameSpace' of the schema.

which seems to indicate that something is using the default ('') namespace, but I have very carefully specified the xlmns and the target namespaces. I don't understand what the error message means by "The targetNamespace parameter ' ' …" – the targetNamespace attribute is specified and is not blank (' ') – I don't know what a "parameter" is in xml terms – or is it referring to something in (or missing from) the C# code?
Can anyone shed any light?

Best Answer

I have not encountered this issue, but I believe the reason this is happening is that xsi:noNamespaceSchemaLocation is for actually indicating the XSD location for XML that has no namespace. Your XML actually has a namespace, so I believe you should replace that attribute with:

xsi:schemaLocation="PM-NameSpace SysConfig.xsd"