Share via


xs:any

The xs:any element provides a flexible mechanism for including schemas from different namespaces. Depending upon your requirements, you can enforce varying levels of restrictions on what is allowed and what is denied through the namespace and processContents attributes.

Consider three schemas: Chimpanzee, Gibbon and Serval. Each schema tracks the same attributes -- Name, Birthdate and FavoriteFood. The Chimpanzees and Gibbons belong to the Primate namespace while the Servals belong to the Cat namespace. Contrived, but stay with me.

Let's say you wanted to throw an exclusive party for primates at your Hollywood Hills mansion and need to draw up a list of primates to invite. You do know a few cats but would rather not invite them to this party -- you had a few servals over for lunch and they clawed up your antique rugs. One approach is to create a new schema named "Primates", include the Chimpanzee and Gibbon schemas, then define two Record elements taking care to set one Data Structure Type to Chimpanzee and one to Gibbon. Done and not an xs:any tag in site. But what happens if you meet a new primate that is neither chimpanzee or gibbon? 

The answer is to use the xs:any tag. Define a new schema name Primates, rename the root node to Primates, and then add an Any element. To restrict the party to Primates only, set the namespace attribute to https://ProcessContentsExample.Primate. If you test the schema against an instance that contains primates and cats, you will get complaints about the cats but the primates will sail through. Great. But what about schema validation?

If you want to validate the messages from the Primate schema, the validator must be able to find the schemas so you must import them. To do this, click on the <Schema> node and then in the properties window, click on the Imports ellipses button to bring up the import dialog. Click add and then add Chimpanzee. To add Gibbon, you will have to edit the schema file manually -- copy the Chimpanzee node and point it to the Gibbon schema file like so:

<xs:import schemaLocation=".\gibbon.xsd" namespace="https://ProcessContentsExample.Primate" />

Now you can click on the Any node and change processContents to strict. If you test the schema now, it should validate provided you have valid primates. Note that with validaton, you will have to modify the schema to include new primates as they are added so you do lose flexibility at the expense of validity.

Use the enclosed sample project to monkey (hah hah) around with different settings of namespace and processContents. Try adding other nodes to the Primate schema and setting a max occurs, then removing the namespace constraint on the Any node. If you do this correctly Visual Studio will complain because the content model is ambiguous -- the new nodes you added can be matched with the Any node.  

Grape Ape

 

ProcessContentsExample.zip

Comments