I am working with multiple XElement
objects to provide some user-specified data for several objects in my library. I'm trying to avoid specifying the structure of the entire XML file because the library shouldn't care what the entire XML looks like as long as the specific elements it needs are structured correctly.
To that end, I have 3 separate XSD
files that define schema for each of the 3 XElements
my class needs, however I am running into some problems validating the XElement against the schema. There doesn't appear to be a method to do that without a workaround.
From the MSDN page, the XElement.Validate()
extension method appears to be geared to re-validating sub-elements of a larger file. The XmlSchemaObject
argument is causing my problems as I cannot assume it will be present in any of the XElements
. I think I can work around this issue by grabbing the XmlSchemaElement
from my XmlSchemaSet
to pass as the XmlSchemaObject
argument, but since the XmlSchemaSet
already defines everything, it seems strange to have to do that.
Is there a better option for validating an XElement
with a schema without first validating the entire XDocument
?
Or should i just let the business layer handle the schema validation in the application and let the library assume the XElement
is properly formed (I considered this option, but as a personal preference prefer to avoid throwing exceptions and would rather just let the calling method know that the XElement
is invalid via a return parameter).
I understand the problem you have with the provided API, as far as I see it you have two options, one being to put your XElement
into an XDocument
with e.g. XDocument doc = new XDocument(xElementToValidate);
and then to call the Validate
method on that XDocument
where all you have to pass in is the XmlSchemaSet
, the second option being the way you outlined yourself, namely to use the Validate
method of the XElement
, making sure you pass in the XmlSchemaSet
and the root element definition in that schema set as the XmlSchemaObject
. If these are simple schemas with just one top level element definition all you have to do is e.g.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "schema.xsd");
schemaSet.Compile();
XmlSchemaObject schemaObject = schemaSet.GlobalElements.Values.OfType<XmlSchemaObject>().First();
If you wrap one of the two approaches into a method then it shouldn't be any more effort than calling a similar convenience method the .NET framework could have supplied.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With