简体   繁体   中英

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">arun@rediff.com</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">rahul@gmail.com</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>

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM