posts - 431,  comments - 344,  trackbacks - 0

SchemaValidation .java

package com.founder.xml;

import Java.io.IOException;
import Java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class SchemaValidation {

 /**
  * @param args
  * @throws IOException
  * @throws SAXException
  * @throws ParserConfigurationException
  */
 public static void main(String[] args) throws ParserConfigurationException,
   SAXException, IOException {
  SchemaValidation sv = new SchemaValidation();
  sv.validate();
 }

 public void validate() {
  try {
   String strLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
   SchemaFactory factory = SchemaFactory.newInstance(strLang);

   InputStream isSchema = getClass().getResourceAsStream("/founder.xsd");
   StreamSource ss = new StreamSource(isSchema);
   Schema schema = factory.newSchema(ss);

   Validator validator = schema.newValidator();
   
   InputStream isXML = getClass().getResourceAsStream("/founder.xml");
   
   StreamSource source = new StreamSource(isXML);
   validator.validate(source);
   System.out.println("Result : Valid!");

  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Result : Invalid!");
  }

 }

}


founder.xsd

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns="http://www.founder.com" elementFormDefault="qualified">
 <xs:element name="note">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="to" type="xs:string" />
    <xs:element name="from" type="xs:string" />
    <xs:element name="heading" type="xs:string" />
    <xs:element name="body" type="xs:string" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>


founder.xml

<?xml version="1.0"?>
<note xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.founder.com founder.xsd">
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
</note>



posted on 2008-03-27 21:46 周锐 阅读(2224) 评论(1)  编辑  收藏 所属分类: JavaXML

只有注册用户登录后才能发表评论。


网站导航: