开发者

XML validation using Java Code [duplicate]

开发者 https://www.devze.com 2023-01-22 07:43 出处:网络
This question already has an answer here: Closed 12 years ago. Possible Duplicate: XML validation using Java Code
This question already has an answer here: Closed 12 years ago.

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>
    &l开发者_开发百科t;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">

  <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...


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消