XML Schema XElement Validation

I work with multiple XElement objects to provide some user data for several objects in my library. I try to avoid specifying the structure of the whole XML file, because the library does not care what the whole XML looks like if the specific elements that it needs are properly structured.

To this end, I have 3 separate XSD files that define a schema for each of the 3 XElements needs of my class, however I run into some problems checking the XElement for a schema. There seems to be no way to do this without a workaround.

On the MSDN page, there is an XElement.Validate() method designed to re-check subelements of a larger file. The XmlSchemaObject argument XmlSchemaObject causing my problems since I cannot assume that it will be present in any of the XElements . I think I can get around this problem by capturing the XmlSchemaElement from my XmlSchemaSet to pass as an argument to XmlSchemaObject , but since XmlSchemaSet already defines everything, it seems strange to do it.

Is there a better option for validating an XElement with a schema without first checking the entire XDocument ?

Or should I just let the business layer handle the validation of the schema in the application and let the library assume that the XElement correctly XElement (I considered this option, but since personal preferences prefer to avoid throwing exceptions and rather just let the calling method know that XElement is invalid using return parameter).

+6
source share
1 answer

I understand what you have with the API provided, as far as I understand, you have two options, one of which is to add XElement to XDocument , for example. XDocument doc = new XDocument(xElementToValidate); and then call the Validate method on the XDocument , where all you need to pass is the XmlSchemaSet , the second option is how you set yourself up, namely use the Validate method for XElement , making sure that you pass the root element definition to the XmlSchemaSet in this schema set as XmlSchemaObject . If these are simple schemas with one top-level element definition, all you need to do, for example,

  XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(null, "schema.xsd"); schemaSet.Compile(); XmlSchemaObject schemaObject = schemaSet.GlobalElements.Values.OfType<XmlSchemaObject>().First(); 

If you transfer one of the two approaches to a method, then it should not be more effort than calling a similar convenience method that the .NET platform could provide.

+9
source

Source: https://habr.com/ru/post/912182/


All Articles