vika
vika

Reputation: 81

validation XML against XSD java

When I validate my xml online all is good. But when in eclipse it doesn't work. It's return an error:

SAX Exception: schema_reference.4: Failed to read schema document 'file:/C:/Users/ASUS/Downloads/Task3_XML/Task3_XML/weapon.xml', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not .

This is my code

public static void main(String[] args) {
     boolean isValid = validateXMLSchema("weapon.xml","weaponXSD.xml");
     if(isValid){
        System.out.println(args[1] + " is valid against " + args[0]);
     }else {
        System.out.println(args[1] + " is not valid against " + args[0]);
     }
  }


public static boolean validateXMLSchema(String xsdPath, String xmlPath){
  try {
     SchemaFactory factory = 
        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
     Schema schema = factory.newSchema(new File(xsdPath));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new File(xmlPath)));
  } catch (IOException e){    
     System.out.println("Exception: "+e.getMessage());
     return false;
  }catch(SAXException e1){
     System.out.println("SAX Exception: "+e1.getMessage());
     return false;
  }
  return true;
}

My XML:

<?xml version="1.0" encoding="UTF-8"?>
<Gun>
  <Weapon>
    <Model>Пістолет «Форт-12»</Model>
    <Handy>one-handed</Handy>
    <Origin>Україна</Origin>
    <TTH>
      <carry>близька [0;500 m]</carry>
      <effectiveRange>10 m</effectiveRange>
      <availabilityClips>true</availabilityClips>
      <availabilityOptics>false</availabilityOptics>
    </TTH>
    <Material>метал</Material>
  </Weapon>
</Gun>

And my XSD in short form:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"      xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Gun">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Weapon" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Model">`

Please if you have any idea write me because i don't understand where there is a problem really.

Upvotes: 0

Views: 477

Answers (1)

A4L
A4L

Reputation: 17595

The error says

file:/C:/Users/ASUS/Downloads/Task3_XML/Task3_XML/weapon.xml

is not an XSD file.

You are passing the xml file as first parameter to the method validateXMLSchema while it expects as first parameter the xsd file.

You need to call that method like this:

boolean isValid = validateXMLSchema("weaponXSD.xml", "weapon.xml");

Also please change the extension of your schema file to .xsd

weaponXSD.xsd

or simply

weapon.xsd

Upvotes: 1

Related Questions