I have a sample code in which i am trying to validate a xml using xml validation method.
And it works correctly too except for minOccurs.I have given the code below. Please help me to find my mistake.
XSD File (Live.xsd):-
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="Test" />
<xsd:complexType name="Test">
<xsd:sequence>
<xsd:element ref="player" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="player" >
<xsd:complexType>
<xsd:sequence minOccurs="2">
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="address">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="houseno" type="xsd:int" />
<xsd:element name="street" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" />
</xsd:complexType>
</xsd:element>
</xsd:schema>
Xml file (example.xml) :-
<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="Live.xsd" >
<player id="1">
<name>Owen</name>
<address>
<houseno>10</houseno>
<street>downing hill</street>
</address>
</player>
</Test>
Java method :-
private void validate(File xml) {
try {
url = new URL(xsd.toURI().toString());//xsd
} catch (MalformedURLException e) {
e.printStackTrace();
}
source = new StreamSource(xml); //xml
try {
System.out.println(url);
schema = schemaFactory.newSchema(url);
} catch (SAXException e) {
e.printStackTrace();
}
validator = schema.newValidator();
System.out.println(xml);
try {
validator.validate(source);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I tried giving minOccurs=2 inside < xsd element ref=”player” /> too but didint work
Remember that the default value for maxOccurs is 1. You’re allowing a minimum of 2 and a maximum of 1 …
Try
<xsd:sequence minOccurs="2" maxOccurs="unbounded">Edit: careful with ‘unbounded’ though; you’d want to set it to an acceptable maximum without giving anyone the chance of bombarding your system with a gazillion of nodes.
Edit2: provided the xsd (corrected with maxOccurs) and xml above, this code will output “Validation failed!!!”:
If you change the code to validate the following example2.xml, it will output “Validation succesful!”:
Your xsd with the minOccurs=2 forces you to have the sequence name-address twice in the xml. Not sure if that’s what you were looking for in the first place; it strikes me as odd but I don’t have insight in the requirements.