views:

45

answers:

1

Possible Duplicate:
XML validation using Java Code

Hi,

I need some code sample which shows how i can validate a xml file against a schema...

Below is say my XML document.. "a.xml"

<?xml version="1.0"?>

<birthdate>
    <month>January</month>
    <day>21</day>
    <year>1983</year>
</birthdate>

Say the schema against which i want to validate the above xml is as below named "XMLValidationSchema.xsd"

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;

  <xs:import namespace="http://www.w3.org/XML/1998/namespace"
        schemaLocation="http://www.w3.org/2001/xml.xsd" />

  <xs:element name="birthdate">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="month" type="xs:string" />
        <xs:element name="day" type="xs:int" />
        <xs:element name="year" type="xs:int" />
      </xs:sequence>  
    </xs:complexType>
  </xs:element>

</xs:schema>

Now can some one help me write the java code that will take these as input and give proper output like if the XML doc is a valid doc as per the schema i specified...

+1  A: 

You need a "validating XML parser" to do this; there are many options available.

Actually, the JDK ships with a validating parser (since JDK 5).

This is a nice tutorial for how to validate a document:

http://java.sun.com/developer/technicalArticles/xml/validationxpath/

It has complete code examples.

If you use a different parser, the principle will be similar (though the exact code used might differ a bit).

sleske
I tried with that code already..