news.Confirmation.java Source code

Java tutorial

Introduction

Here is the source code for news.Confirmation.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package news;

import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;

/**
 *
 * @author Andy
 */
public class Confirmation {
    public static void main(String[] args) {
        validateXMLByXSD();
        validateXMLByDTD();
    }

    public static void validateXMLByXSD() {
        String xmlFileName = "C:\\Users\\Andy\\Documents\\NetBeansProjects\\WebService\\build\\web\\XML\\HomeNews.xml";
        String xsdFileName = "C:\\Users\\Andy\\Documents\\NetBeansProjects\\WebService\\web\\Schmea.xsd";
        try {
            //XML? 
            XMLErrorHandler errorHandler = new XMLErrorHandler();
            //? SAX ? 
            SAXParserFactory factory = SAXParserFactory.newInstance();
            //??? XML  
            factory.setValidating(true);
            //????? XML ??? 
            factory.setNamespaceAware(true);
            //??? SAXParser  
            SAXParser parser = factory.newSAXParser();
            //? 
            SAXReader xmlReader = new SAXReader();
            //??xml 
            Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName));
            // XMLReader ? [url]http://sax.sourceforge.net/?selected=get-set[/url]  
            parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
            //SAXValidator 
            SAXValidator validator = new SAXValidator(parser.getXMLReader());
            //????? 
            validator.setErrorHandler(errorHandler);
            // 
            validator.validate(xmlDocument);

            XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
            //???? 
            if (errorHandler.getErrors().hasContent()) {
                System.out.println("XMLXSD?");
                writer.write(errorHandler.getErrors());
            } else {
                System.out.println("Good! XMLXSD??");
            }
        } catch (Exception ex) {
            System.out.println("XML: " + xmlFileName + " XSD:" + xsdFileName
                    + "\n " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    /** 
     * DTDXML 
     */
    public static void validateXMLByDTD() {
        //todo???? 
    }

}