Sanni
Sanni

Reputation: 57

Validate XML element appearance for alteast 2 times using XMLToJAXB transformer in Mule and validate to must have value

I have POJO classes (created by xjc with a XSD file) that is required for converting XML(with an element(UserField) that should be present alteast 2 times) into JAXB object in Mule. But, if I am giving XML input with presence of UserField less than 2 times then still XMLToJAXB transformer is creating its object while I want there to have some exception or error. And one more thing is that how can I validate UserField must have value using XML Schema.

The XML and XSD files are as under:

userRecords.xml_____________________________________________________

<?xml version='1.0' encoding='UTF-8'?>
<Records>
    <Record>
        <UserField  name="username">arungupta</UserField>
        <UserField  name="email">[email protected]</UserField>
    </Record>    
    <Record>
        <UserField  name="username">RahulKumar</UserField>
        <UserField  name="first name">Rahul</UserField>
        <UserField  name="last name">Kumar</UserField>
        <UserField  name="age">25</UserField>
        <UserField  name="email">[email protected]</UserField>
    </Record>    
</Records>

userRecords.xsd_____________________________________________________________

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="Records">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="Record"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="Record">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="UserField"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="UserField">
    <xs:complexType mixed="true">
      <xs:attribute name="name" use="required"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

Upvotes: 0

Views: 99

Answers (1)

David Dossot
David Dossot

Reputation: 33413

You need first to fix the schema element for Record to add the missing minOccurs attribute:

<xs:element minOccurs="2"
            maxOccurs="unbounded"
            ref="UserField"/>

Then you need to use the XML validation filter before the JAX-B transformer:

<mule-xml:schema-validation-filter schemaLocations="userRecords.xsd"/>

(this assumes that userRecords.xsd is at the root of the classpath)

Upvotes: 1

Related Questions