views:

16

answers:

1

My requirement is to validate an xml with two different validation strategies. In strategy 1, the xml is required to have instances of an element with certain required attributes. In strategy 2, the xml is required to have instances of the same element with different required attributes. So, the idea is that there are two different sets of the same element with different set of required attributes for each set. Is there a way to validate this with using only one xsd. My only solution so far is to use two different xsd files to validate.

Example 1:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element firstName="something"/> <!--required -->
    <element lastName="something"/> <!-- required -->
 <element phoneNumber="something"/> <!-- not required -->
<root>

Example 2:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element firstName="something"/> <!-- not required -->
    <element lastName="something"/> <!-- required -->
 <element phoneNumber="something"/> <!-- required -->
<root>

Can the validation by xsd be achieved?

A: 

Rick,

I've had similar problems to solve in our apps, and our best solution has been to use modularized schemas.

So instead of having Schema1 and Schema2 that are duplicates of each other except for the part that's different, you have Schema1 and Schema2 that include only the constraints that are different, and both import a common Schema3 that defines the constraints that are shared.

An example of how to do that is here.

It doesn't give you a single XSD, but it does reduce duplication, so it helps with maintainability and helps avoid the likelihood of errors creeping in when you have much duplication between Schema1 and Schema2.

The disadvantage is that the schemas become a little more difficult for humans to follow, because the definitions are split up between different files.

LarsH