Is it possible to check the following xml with the following schema? I would like to check the xml without specifying the schema in the XML file.
I am not sure if this is possible or not, but I would appreciate help in figuring out how to do this.
I keep getting the following error while trying to validate an XML file.
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'contacts'.
<?xml version="1.0" ?>
<contacts>
<contact>
<names>Joe Buddah</names>
<address>123 Black Jack Cove</address>
<phone>555-555-1212</phone>
</contact>
<contact>
<name>Ray Buddah</name>
<address>123 Black Jack Cove</address>
<phone>555-555-1212</phone>
</contact>
</contacts>
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://madeupdomain.com/xml/contacts" xmlns:tns="http://madeupdomain.com/contacts" elementFormDefault="qualified">
<complexType name="contactType">
<sequence>
<element name="name" type="string" maxOccurs="1" minOccurs="1"></element>
<element name="address" type="string"></element>
<element name="phone" type="string"></element>
</sequence>
</complexType>
<complexType name="contactsType">
<sequence>
<element name="contact" type="tns:contactType" minOccurs="0" maxOccurs="unbounded"></element>
</sequence>
</complexType>
<element name="contacts" type="tns:contactsType"></element>
</schema>
Java code that I use for verification.
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setAttribute(JAXP_SCHEMA_SOURCE, new File("src/main/resources/contacts.xsd"));
DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
Document document = parser.parse(new File("src/main/resources/contacts.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaFile = new StreamSource(new File("src/main/resources/patient.xsd"));
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try
{
validator.validate(new DOMSource(document));
}
catch (SAXException e)
{
e.printStackTrace();
}
source
share