Is it possible to xsd-validate is an element with exact Attribute exists?

1.1k views Asked by At

I am planning to receive that structure:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <property key="DocumentType"   value="INV" />
    <property key="InvInternalNumber" value="i-1651-84" />
    <property key="OtherDynamicProperty" value="yes" />
</Document>

I identify document type and going to validate with "INV.xsd"

Oh, business say that Invoice must have "InvInternalNumber" property!

So, Is it possible to xsd validate "Is there a property "InvInternalNumber" " ?

UPDATE That XSD has been generated by JaxbContext.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Document" type="Document"/>

  <xs:complexType name="Document">
    <xs:sequence>
      <xs:element name="property" type="property" nillable="true" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="property">
    <xs:sequence/>
    <xs:attribute name="key" type="xs:string"/>
    <xs:attribute name="value" type="xs:string"/>
  </xs:complexType>
</xs:schema>
2

There are 2 answers

0
Michael Kay On BEST ANSWER

XSD 1.0 isn't designed for this job: it assumes that the element name determines the validation rules to apply. One way to tackle it is to transform the XML (using XSLT) to

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <DocumentType>INV</DocumentType>
    <InvInternalNumber>i-1651-84</InvInternalNumber>
    <OtherDynamicProperty>yes</OtherDynamicProperty>
</Document>

and then validate that. (You can achieve this in a single step by using a schema-aware transformation and validating the result document).

Where the validation rules are determined not by the element name, but by the value of an attribute (in your case property/@key), the new feature of Conditional Type Assignment in XSD 1.1 can be used. This allows you to declare that the type of the property element (and hence, the type of its value attribute) depends on the value of the key attribute.

0
Sprotty On

It seems this is not possible in XSD 1.0, I thought if you made the assumption that InvInternalNumber was always the first element you may be able to use the fixed attribute to do it like this, but unfortunately this is not valid.

Error cos-element-consistent: Error for type 'Document'. Multiple elements with name 'property', with different types, appear in the model group.

So as @Dag says I think the only solution is available in XSD 1.1 in the link provided.

enter image description here