jeudi 30 juillet 2009
java : valider un XML par un shema
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/SimpleSchema"
xmlns:tns="http://www.example.org/SimpleSchema" elementFormDefault="qualified">
<element name="Personne" type="tns:Identite"></element>
<complexType name="Identite">
<sequence>
<element name="nom" type="string"></element>
<element name="prenom" type="string"></element>
<element name="age" type="nonNegativeInteger"></element>
<element name="naissance" type="date"></element>
<element name="dureeSession" type="time"></element>
<element name="email" type="tns:emailType"></element>
</sequence>
</complexType>
<simpleType name="emailType">
<restriction base="string">
<minLength value="10"></minLength>
<maxLength value="20"></maxLength>
<pattern value="(\w)+(@)(\w.)+(fr|com)"></pattern>
</restriction>
</simpleType>
</schema>
et le code java qui va bien :
package com.enwoo;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ValidateurXML {
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
File schema = new File("ressources/SimpleSchema.xsd");
ValidateurXML validateurXML= new ValidateurXML();
if(!schema.exists())
{
System.err.println("Schema introuvable");
}
else
{
dbf.setAttribute(JAXP_SCHEMA_SOURCE,schema);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(validateurXML.new MyErrorHandler());
Document doc = db.parse(new File("ressources/Personnes.xml"));
}
}
private class MyErrorHandler implements ErrorHandler
{
public void error(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
}
un très bonne exemple ...
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire