<p>I'm generating some xml files that needs to conform to an xsd file that was given to me.  How should I verify they conform?</p>

[{'answer_id': 15739, 'author': 'SCdF', 'author_id': 1666, 'author_profile': 'https://Stackoverflow.com/users/1666', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s how to do it using <a href="http://xerces.apache.org/xerces2-j/" rel="noreferrer">Xerces2</a>. A tutorial for this, <a href="http://www.ibm.com/developerworks/edu/x-dw-xvalid-i.html" rel="noreferrer">here</a> (req. signup).</p>\n\n<p>Original attribution: blatantly copied from <a href="http://forums.sun.com/thread.jspa?messageID=3411478" rel="noreferrer">here</a>:</p>\n\n<pre><code>import org.apache.xerces.parsers.DOMParser;\nimport java.io.File;\nimport org.w3c.dom.Document;\n\npublic class SchemaTest {\n  public static void main (String args[]) {\n      File docFile = new File("memory.xml");\n      try {\n        DOMParser parser = new DOMParser();\n        parser.setFeature("http://xml.org/sax/features/validation", true);\n        parser.setProperty(\n             "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", \n             "memory.xsd");\n        ErrorChecker errors = new ErrorChecker();\n        parser.setErrorHandler(errors);\n        parser.parse("memory.xml");\n     } catch (Exception e) {\n        System.out.print("Problem parsing the file.");\n     }\n  }\n}\n</code></pre>\n'}, {'answer_id': 15741, 'author': 'Adam', 'author_id': 1366, 'author_profile': 'https://Stackoverflow.com/users/1366', 'pm_score': 0, 'selected': False, 'text': '<p>Are you looking for a tool or a library?</p>\n\n<p>As far as libraries goes, pretty much the de-facto standard is <a href="http://xerces.apache.org" rel="nofollow noreferrer">Xerces2</a> which has both <a href="http://xerces.apache.org/xerces-c/" rel="nofollow noreferrer">C++</a> and <a href="http://xerces.apache.org/xerces2-j/" rel="nofollow noreferrer">Java</a> versions.</p>\n\n<p>Be fore warned though, it is a heavy weight solution. But then again, validating XML against XSD files is a rather heavy weight problem.</p>\n\n<p>As for a tool to do this for you, <a href="http://www.xmlfox.com/xml_editor.htm" rel="nofollow noreferrer">XMLFox</a> seems to be a decent freeware solution, but not having used it personally I can\'t say for sure.</p>\n'}, {'answer_id': 16054, 'author': 'McDowell', 'author_id': 304, 'author_profile': 'https://Stackoverflow.com/users/304', 'pm_score': 9, 'selected': True, 'text': '<p>The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html" rel="noreferrer">javax.xml.validation.Validator</a>.</p>\n\n<pre><code>import javax.xml.XMLConstants;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.*;\nimport java.net.URL;\nimport org.xml.sax.SAXException;\n//import java.io.File; // if you use File\nimport java.io.IOException;\n...\nURL schemaFile = new URL("http://host:port/filename.xsd");\n// webapp example xsd: \n// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");\n// local file example:\n// File schemaFile = new File("/location/to/localfile.xsd"); // etc.\nSource xmlFile = new StreamSource(new File("web.xml"));\nSchemaFactory schemaFactory = SchemaFactory\n    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\ntry {\n  Schema schema = schemaFactory.newSchema(schemaFile);\n  Validator validator = schema.newValidator();\n  validator.validate(xmlFile);\n  System.out.println(xmlFile.getSystemId() + " is valid");\n} catch (SAXException e) {\n  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);\n} catch (IOException e) {}\n</code></pre>\n\n<p>The schema factory constant is the string <code>http://www.w3.org/2001/XMLSchema</code> which defines XSDs. The above code validates a WAR deployment descriptor against the URL <code>http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd</code> but you could just as easily validate against a local file.</p>\n\n<p>You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren\'t going to use them.</p>\n'}, {'answer_id': 158781, 'author': 'KnomDeGuerre', 'author_id': 24233, 'author_profile': 'https://Stackoverflow.com/users/24233', 'pm_score': -1, 'selected': False, 'text': "<p>I had to validate an XML against XSD just one time, so I tried XMLFox. I found it to be very confusing and weird. The help instructions didn't seem to match the interface.</p>\n\n<p>I ended up using LiquidXML Studio 2008 (v6) which was much easier to use and more immediately familiar (the UI is very similar to Visual Basic 2008 Express, which I use frequently). The drawback: the validation capability is not in the free version, so I had to use the 30 day trial.</p>\n"}, {'answer_id': 488685, 'author': 'Todd', 'author_id': 53036, 'author_profile': 'https://Stackoverflow.com/users/53036', 'pm_score': 2, 'selected': False, 'text': '<p>If you are generating XML files programatically, you may want to look at the <a href="http://xmlbeans.apache.org/" rel="nofollow noreferrer">XMLBeans </a>library. Using a command line tool, XMLBeans will automatically generate and package up a set of Java objects based on an XSD.  You can then use these objects to build an XML document based on this schema.</p>\n\n<p>It has built-in support for schema validation, and can convert Java objects to an XML document and vice-versa.</p>\n\n<p><a href="http://www.castor.org/" rel="nofollow noreferrer">Castor</a> and <a href="http://java.sun.com/developer/technicalArticles/WebServices/jaxb/" rel="nofollow noreferrer">JAXB</a> are other Java libraries that serve a similar purpose to XMLBeans.</p>\n'}, {'answer_id': 690450, 'author': 'StaxMan', 'author_id': 59501, 'author_profile': 'https://Stackoverflow.com/users/59501', 'pm_score': 2, 'selected': False, 'text': '<p>One more answer: since you said you need to validate files you are <strong>generating</strong> (writing), you might want to validate content while you are writing, instead of first writing, then reading back for validation. You can probably do that with JDK API for Xml validation, if you use SAX-based writer: if so, just link in validator by calling \'Validator.validate(source, result)\', where source comes from your writer, and result is where output needs to go.</p>\n\n<p>Alternatively if you use Stax for writing content (or a library that uses or can use stax), <a href="https://github.com/FasterXML/woodstox" rel="nofollow noreferrer">Woodstox</a> can also directly support validation when using XMLStreamWriter. Here\'s a <a href="http://www.cowtowncoder.com/blog/archives/2006/08/entry_17.html" rel="nofollow noreferrer">blog entry</a> showing how that is done:</p>\n'}, {'answer_id': 6690151, 'author': 'chickeninabiscuit', 'author_id': 3966, 'author_profile': 'https://Stackoverflow.com/users/3966', 'pm_score': 4, 'selected': False, 'text': '<p>We build our project using ant, so we can use the schemavalidate task to check our config files:</p>\n\n<pre><code>&lt;schemavalidate&gt; \n    &lt;fileset dir="${configdir}" includes="**/*.xml" /&gt;\n&lt;/schemavalidate&gt;\n</code></pre>\n\n<p>Now naughty config files will fail our build!</p>\n\n<p><a href="http://ant.apache.org/manual/Tasks/schemavalidate.html" rel="noreferrer">http://ant.apache.org/manual/Tasks/schemavalidate.html</a></p>\n'}, {'answer_id': 9826988, 'author': 'juwens', 'author_id': 534812, 'author_profile': 'https://Stackoverflow.com/users/534812', 'pm_score': 2, 'selected': False, 'text': '<p>If you have a Linux-Machine you could use the free command-line tool SAXCount. I found this very usefull.</p>\n\n<pre><code>SAXCount -f -s -n my.xml\n</code></pre>\n\n<p>It validates against dtd and xsd.\n5s for a 50MB file.</p>\n\n<p>In debian squeeze it is located in the package "libxerces-c-samples".</p>\n\n<p>The definition of the dtd and xsd has to be in the xml! You can\'t config them separately.</p>\n'}, {'answer_id': 16518985, 'author': 'Paulo Fidalgo', 'author_id': 1006863, 'author_profile': 'https://Stackoverflow.com/users/1006863', 'pm_score': 3, 'selected': False, 'text': '<p>Using Java 7 you can follow the documentation provided in <a href="http://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html" rel="nofollow noreferrer">package description</a>.</p>\n<blockquote>\n<pre><code>// create a SchemaFactory capable of understanding WXS schemas\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\n// load a WXS schema, represented by a Schema instance\nSource schemaFile = new StreamSource(new File(&quot;mySchema.xsd&quot;));\nSchema schema = factory.newSchema(schemaFile);\n\n// create a Validator instance, which can be used to validate an instance document\nValidator validator = schema.newValidator();\n\n// validate the DOM tree\ntry {\n    validator.validate(new StreamSource(new File(&quot;instance.xml&quot;));\n} catch (SAXException e) {\n    // instance document is invalid!\n}\n</code></pre>\n</blockquote>\n'}, {'answer_id': 41225329, 'author': 'rogerdpack', 'author_id': 32453, 'author_profile': 'https://Stackoverflow.com/users/32453', 'pm_score': 4, 'selected': False, 'text': '<p>Since this is a popular question, I will point out that java can also validate against &quot;referred to&quot; xsd\'s, for instance if the .xml file itself specifies XSD\'s in the header, using <code>xsi:schemaLocation</code> or <code>xsi:noNamespaceSchemaLocation</code> (or xsi for particular namespaces) <a href="http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi/index.html" rel="nofollow noreferrer">ex</a>:</p>\n<pre><code>&lt;document xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;\n  xsi:noNamespaceSchemaLocation=&quot;http://www.example.com/document.xsd&quot;&gt;\n  ...\n</code></pre>\n<p>or schemaLocation (always a list of namespace to xsd mappings)</p>\n<pre><code>&lt;document xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;\n  xsi:schemaLocation=&quot;http://www.example.com/my_namespace http://www.example.com/document.xsd&quot;&gt;\n  ...\n</code></pre>\n<p>The other answers work here as well, because the .xsd files &quot;map&quot; to the namespaces declared in the .xml file, because they declare a namespace, and if matches up with the namespace in the .xml file, you\'re good.  But sometimes it\'s convenient to be able to have a custom <a href="https://stackoverflow.com/a/2342859/32453">resolver</a>...</p>\n<p>From the javadocs: &quot;If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:&quot;</p>\n<pre><code>SchemaFactory factory = SchemaFactory.newInstance(&quot;http://www.w3.org/2001/XMLSchema&quot;);\nSchema schema = factory.newSchema();\n</code></pre>\n<p>and this works for multiple namespaces, etc.\nThe problem with this approach is that the <code>xmlsns:xsi</code> is probably a network location, so it\'ll by default go out and hit the network with each and every validation, not always optimal.</p>\n<p>Here\'s an example that validates an XML file against any XSD\'s it references (even if it has to pull them from the network):</p>\n<pre><code>  public static void verifyValidatesInternalXsd(String filename) throws Exception {\n    InputStream xmlStream = new new FileInputStream(filename);\n    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n    factory.setValidating(true);\n    factory.setNamespaceAware(true);\n    factory.setAttribute(&quot;http://java.sun.com/xml/jaxp/properties/schemaLanguage&quot;,\n                 &quot;http://www.w3.org/2001/XMLSchema&quot;);\n    DocumentBuilder builder = factory.newDocumentBuilder();\n    builder.setErrorHandler(new RaiseOnErrorHandler());\n    builder.parse(new InputSource(xmlStream));\n    xmlStream.close();\n  }\n\n  public static class RaiseOnErrorHandler implements ErrorHandler {\n    public void warning(SAXParseException e) throws SAXException {\n      throw new RuntimeException(e);\n    }\n    public void error(SAXParseException e) throws SAXException {\n      throw new RuntimeException(e);\n    }\n    public void fatalError(SAXParseException e) throws SAXException {\n      throw new RuntimeException(e);\n    }\n  }\n</code></pre>\n<p>You can avoid pulling referenced XSD\'s from the network, even though the xml files reference url\'s, by specifying the xsd manually (see some other answers here) or by using an &quot;XML catalog&quot; <a href="https://stackoverflow.com/q/25698764/32453">style resolver</a>.  Spring apparently also <a href="https://stackoverflow.com/a/10768972/32453">can intercept</a> the URL requests to serve local files for validations.  Or you can set your own via <a href="https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/SchemaFactory.html#setResourceResolver(org.w3c.dom.ls.LSResourceResolver)" rel="nofollow noreferrer">setResourceResolver</a>, ex:</p>\n<pre><code>Source xmlFile = new StreamSource(xmlFileLocation);\nSchemaFactory schemaFactory = SchemaFactory\n                                .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = schemaFactory.newSchema();\nValidator validator = schema.newValidator();\nvalidator.setResourceResolver(new LSResourceResolver() {\n  @Override\n  public LSInput resolveResource(String type, String namespaceURI,\n                                 String publicId, String systemId, String baseURI) {\n    InputSource is = new InputSource(\n                           getClass().getResourceAsStream(\n                          &quot;some_local_file_in_the_jar.xsd&quot;));\n                          // or lookup by URI, etc...\n    return new Input(is); // for class Input see \n                          // https://stackoverflow.com/a/2342859/32453\n  }\n});\nvalidator.validate(xmlFile);\n</code></pre>\n<p>See also <a href="https://docs.oracle.com/javase/tutorial/jaxp/dom/validating.html" rel="nofollow noreferrer">here</a> for another tutorial.</p>\n<p>I believe the default is to use DOM parsing, you can do something similar with SAX parser that is validating <a href="https://blog.frankel.ch/use-local-resources-when-validating-xml/" rel="nofollow noreferrer">as well</a> <code>saxReader.setEntityResolver(your_resolver_here);</code></p>\n'}, {'answer_id': 47514401, 'author': 'razvanone', 'author_id': 2148681, 'author_profile': 'https://Stackoverflow.com/users/2148681', 'pm_score': 2, 'selected': False, 'text': '<p>With JAXB, you could use the code below:</p>\n\n<pre><code>    @Test\npublic void testCheckXmlIsValidAgainstSchema() {\n    logger.info("Validating an XML file against the latest schema...");\n\n    MyValidationEventCollector vec = new MyValidationEventCollector();\n\n    validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);\n\n    assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));\n}\n\nprivate void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class&lt;?&gt; rootClass) {\n    try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {\n        final JAXBContext jContext = JAXBContext.newInstance(rootClass);\n        // Unmarshal the data from InputStream\n        final Unmarshaller unmarshaller = jContext.createUnmarshaller();\n\n        final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n        final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);\n        unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));\n\n        unmarshaller.setEventHandler(vec);\n\n        unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate\n\n        for (String validationError : vec.getValidationErrors()) {\n            logger.trace(validationError);\n        }\n    } catch (final Exception e) {\n        logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);\n    }\n}\n\nclass MyValidationEventCollector implements ValidationEventHandler {\n    private final List&lt;String&gt; validationErrors;\n\n    public MyValidationEventCollector() {\n        validationErrors = new ArrayList&lt;&gt;();\n    }\n\n    public List&lt;String&gt; getValidationErrors() {\n        return Collections.unmodifiableList(validationErrors);\n    }\n\n    @Override\n    public boolean handleEvent(final ValidationEvent event) {\n        String pattern = "line {0}, column {1}, error message {2}";\n        String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),\n                event.getMessage());\n        if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {\n            validationErrors.add(errorMessage);\n        }\n        return true; // you collect the validation errors in a List and handle them later\n    }\n}\n</code></pre>\n'}, {'answer_id': 52645727, 'author': 'jschnasse', 'author_id': 1485527, 'author_profile': 'https://Stackoverflow.com/users/1485527', 'pm_score': 0, 'selected': False, 'text': '<p><strong>Validate against online schemas</strong></p>\n\n<pre><code>Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));\nValidator validator = schema.newValidator();\nvalidator.validate(xmlFile);\n</code></pre>\n\n<p><strong>Validate against local schemas</strong></p>\n\n<p><a href="https://stackoverflow.com/a/48447453/1485527">Offline XML Validation with Java</a></p>\n'}, {'answer_id': 58040690, 'author': 'Loris Securo', 'author_id': 6245535, 'author_profile': 'https://Stackoverflow.com/users/6245535', 'pm_score': 1, 'selected': False, 'text': '<p>Using <a href="https://github.com/FasterXML/woodstox" rel="nofollow noreferrer">Woodstox</a>, configure the StAX parser to validate against your schema and parse the XML.</p>\n\n<p>If exceptions are caught the XML is not valid, otherwise it is valid:</p>\n\n<pre><code>// create the XSD schema from your schema file\nXMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);\nXMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);\n\n// create the XML reader for your XML file\nWstxInputFactory inputFactory = new WstxInputFactory();\nXMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);\n\ntry {\n    // configure the reader to validate against the schema\n    xmlReader.validateAgainst(validationSchema);\n\n    // parse the XML\n    while (xmlReader.hasNext()) {\n        xmlReader.next();\n    }\n\n    // no exceptions, the XML is valid\n\n} catch (XMLStreamException e) {\n\n    // exceptions, the XML is not valid\n\n} finally {\n    xmlReader.close();\n}\n</code></pre>\n\n<p><strong>Note</strong>: If you need to validate multiple files, you should try to reuse your <code>XMLInputFactory</code> and <code>XMLValidationSchema</code> in order to maximize the performance.</p>\n'}]
['https://Stackoverflow.com/questions/15732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650/']