17 November 2016

XML TEST: Bài thi thực hành Validation XML vs DTD & XSD truyền 2 tham số args[] [JAVA]

Cấu trúc project
Cách khai báo internal or external DTD và XSD trong file XML [Xem]
note.xml
Java XML 2016
<?xml version="1.0"?>

<!DOCTYPE note SYSTEM "note.dtd"> <!--Validating XML with external DTD-->

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend</body>
</note>
note.dtd
Java XML 2016
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
note.xsd
Java XML 2016
<?xml version="1.0" encoding="UTF-8"?>

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified">
    
    <xsd:element name="note">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="to" type="xsd:string"></xsd:element>
                <xsd:element name="from" type="xsd:string"></xsd:element>
                <xsd:element name="heading" type="xsd:string"></xsd:element>
                <xsd:element name="body" type="xsd:string"></xsd:element>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    
</xsd:schema>
DOMValidation.java
Java XML 2016
package test;

import java.io.IOException;
import java.util.logging.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Document;
import org.xml.sax.*;

/**
 *
 * @author Lonely
 */
public class DOMValidation {

    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 SimpleErrorHandler());
            Document document = builder.parse(new InputSource("src\\database\\" + xmlFile));

        } catch (SAXException ex) {
            Logger.getLogger(DOMValidation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(DOMValidation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DOMValidation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
SAXValidation.java
Java XML 2016
package test;

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 SAXValidation {

    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 SimpleErrorHandler());
            reader.parse(new InputSource("src\\database\\" + xmlFile));

        } catch (SAXException ex) {
            Logger.getLogger(SAXValidation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(SAXValidation.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SAXValidation.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
SimpleErrorHandler.java
Java XML 2016
package test;

import org.xml.sax.*;

/**
 *
 * @author Lonely
 */
public class SimpleErrorHandler 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("Error at line " + e.getLineNumber() + ": ");
        System.out.println(e.getMessage());
    }

}
Main.java
Java XML 2016
package test;

public class Main {

    public static void main(String args[]) {
        
        DOMValidation d = new DOMValidation();
        d.validateDom(args[0], args[1]);

        SAXValidation d1 = new SAXValidation();
        d1.validateSax(args[0], args[1]);

    }
}
Tiếp theo ta sẽ chạy project này bằng Arguments truyền hai tham số vào args[0] args[1] như sau:
B1: Đặt con trỏ vào tên project và click chuột phải
B2: Chọn Properties
 B3: Nhập tên file note.xml và note.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

Khi chạy project báo lỗi như sau:
...Còn rất nhiều lỗi khác.
Download (Zip import NetBeans)

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang