简体   繁体   中英

XML schema unique child elements

I am trying to validate that a parent has unique child elements by the element name. I also need to validate that at least one of the possible elements exists.

Example

<StorageTypes>
    <Status/>
    <Warning/>  
    <Error/>             
</StorageTypes>  

Would be valid but

<StorageTypes>
    <Status/>
    <Status/>
    <Warning/>  
    <Error/>             
</StorageTypes>  

and

<StorageTypes>               
</StorageTypes>  

would be invalid.

I have tried using xs:unique, selecting the the current node, but am unable to generically select the elements with the field element.

The below acheives what I am looking to do but it is not the robust solution I am looking for. I would like to be able to add more Types with out changing the xpath for every change.

<element ect.>
    <xs:unique name="something">
        <xs:selector xpath="."/>
        <xs:field xpath="Status"/>
        <xs:field xpath="Warning"/>
        <xs:field xpath="Error"/>
    </xs:unique>
</element>

Is this possible? Is this good practice? Any advice would be appreciated.

A generic solution based on XSD 1.0 is not possible. I don't believe your unique achieves what you want either, simply because a field's value is evaluated using text(); so the name of the tag never plays a role in this...

While you may be able to achieve something that is close to what you want, it may not work in all scenarios, or it'll lack elegance or feasability...

Below approaches may not be considered elegant by some... nonetheless, it could serve the same purpose.

For eg, if instead you use an attribute to capture the "tag" name as in:

<StorageTypes>
   <Storage type="Status"/>
   <Storage type="Warning"/>
   <Storage type="Error"/>
</StorageTypes>

Then writing your unique on @type field, combined with a sequence of Storage, maxOccurs=whatever gives you strictly what you've depicted.

If instead you're looking for elements that actually have complex content, or attributes are not allowed, then you could use substitution groups to the same effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM