1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XMLXSDChecker {
/*
* This program is for checking the XML file and XSD schema.
* It uses the class "SimpleErrorHandler" and catch errors in order to create a correct
* XML XSD groupe of files
*/
public void String (String XMLFileName) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
//These 3 lines are for informing that the validation is done via an XSD file.
SchemaFactory sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//The XSD schema is created
//Here, it is an intern schema, for an extern one an URI is required
Schema schema = sfactory.newSchema(new File("ProjectFile.xsd"));
//The schema is assigned to the factory so that the document takes in charge the XSD file
factory.setSchema(schema);
DocumentBuilder builder = factory.newDocumentBuilder();
//Creation of the error handler
ErrorHandler errHandler = new SimpleErrorHandler();
//Assignment of the error handler to the document in order to catch some.
builder.setErrorHandler(errHandler);
File fileXML = new File("ProjectFile.xml");
//A block of capture is added to catch error if there are some.
try {
Document xml = builder.parse(fileXML);
Element root = xml.getDocumentElement();
System.out.println(root.getNodeName());
} catch (SAXParseException e) {}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|