tags:

views:

35

answers:

1

I want to know how to validate XML with XSD . XML is not of an element type but a complex type . Since validator class's validate method compare only element type.

So basically I want to valide XSD's complex type with an XML.

e.g.

Basic XSD below

xs:element name="Customer">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Dob" type="xs:date" />
      <xs:element name="Address">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Line1" type="xs:string" />
            <xs:element name="Line2" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

We can assume we have multiple complex type in the Customer element.

MY XML is

<Address> 
    <Line1>34 thingy street, someplace</Line1> 
    <Line2>sometown, w1w8uu </Line2>
</Address>

How I validate my XML with XSD. Kindly post your suggestions in java

A: 

Something like

import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

//  .....


    try {
        File xmlFile // read XML file

        File xsdFile // read XSD file

        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsdFile);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlFile));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
MarcoS