2009年1月4日

XML Validate with DTD

Wikipedia Document Type Definition
W3C Document Type Definition

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class Main implements ErrorHandler {

public void error(SAXParseException exception) throws SAXException {
throw exception;
}

public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}

public void warning(SAXParseException exception) throws SAXException {
throw exception;
}

public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
ErrorHandler errorHandler = new Main();
builder.setErrorHandler(errorHandler);
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<!DOCTYPE root [")
.append("<!ELEMENT root (user)>")
.append("<!ELEMENT user (name,birthday,address)>")
.append("<!ELEMENT name (#PCDATA)>")
.append("<!ELEMENT birthday (#PCDATA)>")
.append("]>")
.append("<root>")
.append("<user>")
.append("<name>Solnone</name>")
.append("<birthday>1974-01-01</birthday>")
.append("</user>")
.append("</root>");
byte[] buf = sb.toString().getBytes("UTF-8");
InputStream is = new ByteArrayInputStream(buf);
try {
builder.parse(is);
} finally {
is.close();
}
}
}

沒有留言:

網誌存檔