0
votes

I'm using javax.xml.validation.Validator for validating xml against schema. I have a requirement where the input xml contains 'minOccurs' and 'maxOccurs' fields. If I validate this against schema, I'm getting org.xml.sax.SAXParseException; lineNumber: 3; columnNumber: 7; cvc-complex-type.3.2.2: Attribute 'minOccurs' is not allowed to appear in element. How to resolve this?

Validation:

URL url;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
url = classLoader.getResource(schemaLocation);
String xsd = url.toURI().getPath();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File f = new File(xsd);
schema = factory.newSchema(f);
Validator valid = schema.newValidator();
StringReader xml = new StringReader(request);
valid.validate(new StreamSource(xml));
xml.close();

XSD:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="item">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema> 

XML:

<order>  
  <item>
    <name minoccurs="1" maxOccurs="unbounded">apple</name>   
  </item>
</order> 
2

2 Answers

0
votes

Trying to validate your XML againt the provided XSD will give you the following error:

Attribute 'minoccurs' Cannot Appear In Element 'element'.

The XSD Indicators specification tells that Occurrence indicators are :

maxOccurs

minOccurs

With an Uppercase 'O'

Change your XSD to :

<xs:sequence>
    <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>

And your XML to :

<order>  
  <item>
    <name>apple</name>   
  </item>
</order>
0
votes

You shouldn't put minoccurs="1" maxOccurs="unbounded" in the xml element name.

What you need is :

<order>  
  <item>
    <name>apple</name>   
  </item>
</order>

With your current code it's looking for an attribute minoccurs and maxOccurs which you didn't define in your xsd file.

Edit :

If you want to use minOccurs and maxOccurs as attributes of your element name and keep <name minOccurs="1" maxOccurs="unbounded">apple</name> then you need to declare those attributes in your XSD like so.

<xs:complexType>
    <xs:sequence>
        <xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="minOccurs" type="xs:integer"/>
    <xs:attribute name="maxOccurs" type="xs:integer"/>
</xs:complexType>