CodexBloom - Programming Q&A Platform

Trouble with XML Document Validation Against XSD in Java - SchemaLocation Not Found Error

👀 Views: 45 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
xml xsd validation javax Java

I'm trying to figure out I've encountered a strange issue with I'm collaborating on a project where I tried several approaches but none seem to work. I'm having trouble validating an XML document against its XSD schema in Java using the `javax.xml.validation` package. My XML declares the schema location, but I'm getting a `SchemaLocation not found` error at runtime, even though the XSD file is correctly located in the resources folder. Here's my XML snippet: ```xml <book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/bookSchema book.xsd"> <title>Java Programming</title> <author>John Doe</author> </book> ``` And my code for validation looks like this: ```java import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; public class XMLValidator { public static void main(String[] args) { try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File("src/main/resources/book.xsd")); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File("src/main/resources/book.xml"))); System.out.println("XML is valid."); } catch (Exception e) { System.out.println("Validation error: " + e.getMessage()); } } } ``` I've verified that the path to `book.xsd` is correct, and the schema itself is valid. I've even tried using absolute paths to no avail. I've also checked that the XML file is well-formed. Can anyone suggest what might be causing the `SchemaLocation not found` error, or how to properly set the schema location in this case? Any help would be greatly appreciated! For context: I'm using Java on Linux. What's the best practice here? Has anyone else encountered this? The project is a desktop app built with Java.