title: Java xsd validation of xml without namespace
body: <p>I want to validate an XML file against an XSD schema. The XML files root element does not have any namespace or xsi details. It has no attributes so just <code>&lt;root&gt;</code>.</p>
  
  <p>I have tried the following code from <a href="http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html" rel="nofollow noreferrer">http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html</a> with no luck as I receive 
  <code>cvc-elt.1: Cannot find the declaration of element 'root'</code></p>
  
  <pre><code>SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  
  File schemaFile = new File("schema.xsd");
  
  Schema xsdScheme = factory.newSchema(schemaFile);
  
  Validator validator = xsdScheme.newValidator();
  
  Source source = new StreamSource(xmlfile);
  
  validator.validate(source);
  </code></pre>
  
  <p>The xml validates fine with the namespace headers included etc (added via xmlspy), but I would have thought the xml namespace could be declared without having to manually edit the source file?</p>
  
  <p><strong>Edit and Solution:</strong></p>
  
  <pre><code>public static void validateAgainstXSD(File file) {
  
      try {
          SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
  
          File schemaFile = new File("path/to/xsd");
  
          Schema xsdScheme = factory.newSchema(schemaFile);
  
          Validator validator = xsdScheme.newValidator();
  
          SAXSource source = new SAXSource(
                  new NamespaceFilter(XMLReaderFactory.createXMLReader()),
                  new InputSource(new FileInputStream(file)));
  
          validator.validate(source,null);
  
      } catch (Exception e) {
          e.printStackTrace();
      }
  
  }
  
  protected static class NamespaceFilter extends XMLFilterImpl {
  
      String requiredNamespace = "namespace";
  
      public NamespaceFilter(XMLReader parent) {
          super(parent);
      }
  
      @Override
      public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
          if(!arg0.equals(requiredNamespace)) 
              arg0 = requiredNamespace;
          super.startElement(arg0, arg1, arg2, arg3);
      }       
  }
  </code></pre>