validating attribute values of xml elements
I am trying to write a xsd document that validates the following xml snippet.
<parentElement>
<someElement name="somethingRequired"/>
<someElement name="somethingElseRequired"/>
<someElement name="anything"/>
</parentElement>
It shall validate, if parentElement contains at least two occurences of someElement where one has an attribute name containing the value "somethingRequired" and the other has an attribute name containing the value "somethingEls开发者_运维技巧eRequired".
Is that possible?
Is that possible?
It depends on how specific your restrictions need to be. If it is good enough that all of the name
attributes have unique values, then you can achieve this with <xs:unique>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="parentElement">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="2" maxOccurs="unbounded" name="someElement">
<xs:complexType>
<xs:attribute name="name" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:unique name="uniqueName">
<xs:selector xpath="someElement" />
<xs:field xpath="@name" />
</xs:unique>
</xs:element>
</xs:schema>
You can also restrict the attribute values for example to some enumerated set of allowed values instead of just using type="xs:string"
. It is not possible though to restrict only the first two name attributes to be unique because the xpath
attribute is not allowed to contain predicates.
If you need the first name attribute to have some specific value, the second one some other specific value and the rest to have any value, then I would say that this either violates the Schema Component Constraint Element Declarations Consistent or would need some sort of co-occurrence constraint that is more specific than <xs:unique>
so generally it wouldn't be possible. You might be able to make it possible by using xsi:type
attribute in the instance document to explicitly declare the type of the element.
Everything you want to do is possible except for validating based on the attribute values.
精彩评论