Home > Java > javaTutorial > How Can I Validate XML Files Against an XSD File Using Java?

How Can I Validate XML Files Against an XSD File Using Java?

Patricia Arquette
Release: 2024-12-10 04:52:14
Original
621 people have browsed it

How Can I Validate XML Files Against an XSD File Using Java?

Validating XML Files Against an XSD File

Verifying the conformity of generated XML files against a provided XSD file is paramount to ensure adherence to the specified data structure.

Solution: Java Runtime Library Validation

The Java runtime library provides robust validation capabilities through the javax.xml.validation.Validator class. Here's an example code snippet to guide you:

...
URL schemaFile = new URL("http://host:port/filename.xsd");
Source xmlFile = new StreamSource(new File("web.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) {}
Copy after login

In this snippet:

  • schemaFile represents the XSD file to validate against.
  • xmlFile is the XML file to be validated.
  • schemaFactory creates a Schema instance from the schemaFile.
  • validator is created from the Schema.
  • The validate method checks the xmlFile against the XSD.

Note: Avoid using the DOMParser for validation as it consumes unnecessary memory.

The above is the detailed content of How Can I Validate XML Files Against an XSD File Using Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template