Reputation: 1352
I am using following code to validate my xml against xsd.
var isXmlValid = true;
var vinListMessage = "<root xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:test/properties/v1.0\"><test12121 id=\"3\"></test></root>";
var xsdFilePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "schema.xsd");
var schemas = new XmlSchemaSet();
schemas.Add(null, xsdFilePath);
var xmlDocument = XDocument.Parse(vinListMessage);
xmlDocument.Validate(schemas, (o, e) => { isXmlValid = false; });
Console.WriteLine(isXmlValid);
Please note the xmlns in the above xml, its urn:test/properties/v1.0
.
Now in my xsd I have targetnamespace
as targetNamespace="urn:testnew/properties/v1.0"
which is different than in the xml.
Now whatever xml I try to validate against the xsd it always return true. But If I match the namespaces then its working fine. I want to avoid dependency on namespace. Any suggestions?
Upvotes: 0
Views: 2212
Reputation: 26213
The namespace is a part of the element name, so there's not much you can do other than ensure they are correct.
If all the element namespaces are supposed to be the same, you could set the namespace on all your elements before validating:
XNamespace ns = "urn:testnew/properties/v1.0";
foreach (var element in xmlDocument.Descendants())
{
element.Name = ns + element.Name.LocalName;
}
xmlDocument.Validate(...);
Unfortunately, if the namespace doesn't match then the XML is valid according to the schema (provided it is well formed) as the schema simply doesn't apply to the elements. The validation can raise a warning to say the elements aren't recognised, though it's not possible to pass this flag via the XDocument.Validate
extension method (as far as I can tell!).
This question shows an alternate validation method using XmlReader
and XmlReaderSettings
that would allow you to capture warnings if the schema does not recognise elements.
Upvotes: 1