We would like to know how to validate XML against xsd's.
import java.io.File; /* ww w. j a va 2 s . c o m*/ import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.w3c.dom.Document; public class Main { public static void main(String[] args) throws Exception{ SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder(); Document document = parser.parse(new File("NewFile.xml")); Schema schema = schemaFactory.newSchema(new File("NewFile.xsd")); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } }
NewFile.xml:
<tns:fundamo xmlns:p="http://www.java2s.com/xsd/gen_fin" xmlns:tns="http://www.java2s.com/xsd/accList" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.java2s.com/xsd/accList AccountList.xsd "> <tns:response> <p:code>p:code</p:code> <p:description>p:description</p:description> </tns:response> </tns:fundamo>
NewFile.xsd:
<xs:schema/*from www.j a va 2s .com*/ version="1.0" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.java2s.com/xsd/accList" targetNamespace="http://www.java2s.com/xsd/accList" xmlns:common="http://www.java2s.com/xsd/gen_fin"> <xs:import namespace="http://www.java2s.com/xsd/gen_fin" schemaLocation="common.xsd" /> <xs:element name="fundamo"> <xs:complexType> <xs:sequence> <xs:element name="response" type="common:response" minOccurs="1" maxOccurs="1" /> <xs:element name="transaction" type="tns:transaction" minOccurs="0" maxOccurs="1" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="transaction"> <xs:sequence> <xs:element name="transactionRef" type="xs:string" /> <xs:element name="dateTime" type="xs:string" /> <xs:element name="userName" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema>
common.xsd
<xs:schema/*w ww .j a v a2 s . com*/ version="1.0" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns="http://www.java2s.com/xsd/gen_fin" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.java2s.com/xsd/gen_fin"> <xs:complexType name="response"> <xs:sequence> <xs:element name="code" type="xs:string" /> <xs:element name="description" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema>