XSD는 XML Schema Definition이다.
XML이 XSD에 따른 well-formed XML인지 판단하기 위해 web validator들이 많이 있다.
다만 XSD가 여러 개여서 하나가 다른 것들을 포함할 경우 로컬에 두고 그냥 코드로 짜서 판단하는게 편하다. 이미 javax.xml에 validator가 구현되있기 때문이다.
위 stackoverflow 답변을 참고해서 아래 코드를 짜봤다.
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class Val {
public static void main(String args[]) throws IOException, SAXException {
// URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd:
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
File schemaFile = new File("example.xsd");
Source xmlFile = new StreamSource(new File("example.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}
}
}