Ở ví dụ này chúng ta chỉ validate bằng XSD không validate bằng DTD.
Chạy hàm main bằng Argument args[] truyền 2 file sinhvien.xml và sinhvien.xsd
XSD validate những cái gì ?
XSD kiểm tra dữ liệu nhập vào có đúng kiểu khai báo hay không.
VD int, string, double, float, boolean ...
VD int, string, double, float, boolean ...
Cách khai báo internal or external DTD và XSD trong file XML [Xem]
Tìm hiểu về DTD và XSD [Xem]
sinhvien.xml
Java XML 2016
<?xml version="1.0" encoding="UTF-8"?>
<aptech>
<sinhvien id="01">
<masv>sv01</masv>
<hoten>sinh vien 1</hoten>
<tuoi>12</tuoi>
<dtb>6.5</dtb>
<ngaysinh>1881-04-20</ngaysinh>
</sinhvien>
</aptech>
sinhvien.xsd
Java XML 2016
<?xml version="1.0"?>
<xsd:schema version="1.0"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xsd:element name="aptech">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="sinhvien" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="sinhvien">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="masv" type="xsd:string"></xsd:element>
<xsd:element name="hoten" type="xsd:string"></xsd:element>
<xsd:element name="tuoi" type="xsd:int"></xsd:element>
<xsd:element name="dtb" type="xsd:double"></xsd:element>
<xsd:element name="ngaysinh" type="xsd:date"></xsd:element>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:schema>
ValidationDOM.java
Java XML 2016
package validatorxsd_p2;
import java.io.*;
import java.util.logging.*;
import javax.xml.parsers.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.w3c.dom.Document;
import org.xml.sax.*;
/**
*
* @author Lonely
*/
public class ValidationDOM {
public void validateDom(String xmlFile, String xsdFile) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(new Source[]{
new StreamSource("src\\database\\" + xsdFile)
}));
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new MyErrorHandler());
Document document = builder.parse(new InputSource("src\\database\\" + xmlFile));
} catch (SAXException ex) {
Logger.getLogger(ValidationDOM.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(ValidationDOM.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ValidationDOM.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ValidationSAX.java
Java XML 2016
package validatorxsd_p2;
import java.io.IOException;
import java.util.logging.*;
import javax.xml.parsers.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.*;
/**
*
* @author Lonely
*/
public class ValidationSAX {
public void validateSax(String xmlFile, String xsdFile) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[]{new StreamSource("src\\database\\" + xsdFile)
}));
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new MyErrorHandler());
reader.parse(new InputSource("src\\database\\" + xmlFile));
} catch (SAXException ex) {
Logger.getLogger(ValidationSAX.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(ValidationSAX.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ValidationSAX.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
MyErrorHandler.java
Java XML 2016
package validatorxsd_p2;
import org.xml.sax.*;
public class MyErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.print("Warning at line " + e.getLineNumber() + ": ");
System.out.println(e.getMessage());
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.print("Error at line " + e.getLineNumber() + ": ");
System.out.println(e.getMessage());
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.print("Fatal error at line " + e.getLineNumber() + ": ");
System.out.println(e.getMessage());
}
}
Main.java
Java XML 2016
package validatorxsd_p2;
public class Main {
public static void main(String[] args) {
ValidationDOM d = new ValidationDOM();
d.validateDom(args[0] , args[1]);
ValidationSAX v1 = new ValidationSAX();
v1.validateSax(args[0] , args[1]);
}
}
B2: Chọn Properties
B3: Nhập tên file sinhvien.xml và sinhvien.xsd vào ô Arguments cách nhau bằng khoảng trắng rồi nhấn OK
B4: Tiến hành chạy project nhấn F6 để chạy toàn bộ project
-Nếu màn hình successful thì file XML không có lỗi
-Ngược lại lỗi sẽ hiển thị
VD: XML lỗi
-Ngược lại lỗi sẽ hiển thị
VD: XML lỗi
Dữ liệu trong XML đúng
Dữ liệu nhập sai tuổi có cả string
Khi chạy project báo lỗi như sau:
...Còn nhiều lỗi khác.
Download (Zip import NetBeans)
0 nhận xét:
Post a Comment