Choice of Attribute(s) on XML instance for directly defined attributes or references
I'm looking for a variant of choosing an attribute for an elemen开发者_JAVA百科t, that can be directly set or be referenced.
this is what I have in Mind:
<root>
<element>
<attribute ref="shortname" />
</element>
<element>
<attribute name="shortname" isEditable="true" anotherattrib="0815" />
</element>
</root>
Since this wouldn't be problem without an xml scheme, the definition of this attribute is quite hard if attribute "name" of element attribute is required.
the scheme could look like this
<xs:element name="attribute">
<xs:complexType>
<xs:attribute name="ref" use="required" />
<xs:attribute name="name" use="required" />
</xs:complexType>
</xs:element>
Is there any possibility to make a choice ( similar to a xs:choice for elements ) between attributes? Like if there is an attribute from element attribute named ref, no other attributes are allowed. if not, the attribute "name" must be set...
This problem sounds pure virtual and academic but I would be happy if there might be a solution or if I'm completely wrong with what I have in mind :)
Thank you in advance for any help!
Dave
It seems to me that it is impossible to define XML Schema like you want. Either you should define two different element names like <attribute>
and <attributeRef>
with the different set of mandatory attributes or you should define neither "ref"
nor "name"
attribute as "required"
.
XML Schema is not the only way to verify the data and you can not define some roles between the attribute values with respect of XML Schema. So if you do need verify more complex relationship in a XML document you can use XPath and XSLT to do this (see Schematron, XML Schema Language Comparison, Beyond W3C XML Schema, Improving XML Document Validation with Schematron, Advanced XML validation and Using XSL as a Validation Language).
This can be achieved with XML Schema 1.1 assertions:
<xsd:complexType name="AttributeType">
<xsd:sequence />
<xsd:attribute name="ref" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
<xsd:assert test="count(@ref | @name) = 1" />
</xsd:complexType>
The assert
element ensures that only one of ref
and name
are used.
精彩评论