Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Validate tài liệu kết quả của việc transform 1 tài liệu xml

package validatingaftertransform;

import javax.xml.XMLConstants;

import javax.xml.transform.Source;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMResult;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamSource;

import javax.xml.validation.Schema;

import javax.xml.validation.SchemaFactory;

import javax.xml.validation.Validator;

public class ValidatingDOMStream {

public static void main(String[] args) {

String xmlfile = “files/catalog.xml”;

String xsdfile = “files/catalog.xsd”;

try {

TransformerFactory tsf=TransformerFactory.newInstance();

Transformer trs=tsf.newTransformer();

Source src=new StreamSource(xmlfile);

DOMResult result=new DOMResult();//giữ kết quả của việc transform

trs.transform(src, result);

Source schemaFile = new StreamSource(xsdfile);

SchemaFactory factory =

SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema schema = factory.newSchema (schemaFile);

Validator validator = schema.newValidator ();

DOMSource domsrc=new DOMSource(result.getNode());

validator.validate (domsrc);

System.out.println(xmlfile + ” document is valid!”);

} catch (Exception e) {

System.out.println(xmlfile + ” document is NOT valid!”);

System.out.println(e.getMessage());

}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: