问题
I have such xml structure:
<main>
<objects>
<object name="book" />
<object name="table" />
</objects>
<actions>
<action input="book" />
<action input="table" />
<action input="book" />
</actions>
</main>
This is a simplified example.
I want to create xsd schema which invalidates such xml:
<main>
<objects>
<object name="book" />
<object name="table" />
</objects>
<actions>
<action input="book" />
<action input="table" />
<action input="fruit" />
</actions>
</main>
because of there is no object item with the name "fruit" into list of objects.
I can't simply create <xsd:enumeration>
because object names are always different and I don't know all of them. It seems to be a list of possible values of action's names should be created dynamically.
It would be wonderful to create enumeration dynamically for IntelliSense support (<xsd:assert>
can't provide it).
Is it possible?
回答1:
Start with a generated XSD, then tweak it to introduce the constraints you want. The Intellisense part is highly dependent on the editor. Even though the metadata to infer a "smart" intellisense is in there (via key/keyref), I doubt editors in the market would make use of that. The XSD below would validate and fail the XMLs you've provided.
<?xml version="1.0" encoding="utf-8"?>
<!--XML Schema generated by QTAssistant/XML Schema Refactoring (XSR) Module (http://www.paschidev.com)-->
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="main">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="objects">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="object">
<xsd:complexType>
<xsd:attribute name="name" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="actions">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="action">
<xsd:complexType>
<xsd:attribute name="input" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:key name="Objects">
<xsd:selector xpath="objects/object"/>
<xsd:field xpath="@name"/>
</xsd:key>
<xsd:keyref name="ActionToObjects" refer="Objects">
<xsd:selector xpath="actions/action"/>
<xsd:field xpath="@input"/>
</xsd:keyref>
</xsd:element>
</xsd:schema>
The diagram:

来源:https://stackoverflow.com/questions/11701535/dynamical-enumeration-in-xsd