1

How to determine whether a given file is an xml valide file in JAVA?

for example :

bool valide = IsAnXMLFile(new File("file.txt"));

Thank's.

AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • 1
    You mean valid as *well formed* or as *valid according to a schema*? – meskobalazs Oct 30 '14 at 11:12
  • 3
    If you want to check against an XML-Schema check this question: http://stackoverflow.com/questions/15732/whats-the-best-way-to-validate-an-xml-file-against-an-xsd-file – duffy356 Oct 30 '14 at 11:19
  • 1
    try to check this answer: http://stackoverflow.com/questions/6362926/xml-syntax-validation-in-java – drgPP Oct 30 '14 at 11:23

2 Answers2

1

you can check well-formedness just by loading the file with a parser. if the file references a dtd then it is also validated against this dtd (this requires the dtd to be present at the specified place). If you use a schema language (f.i. xsd) then you need to validate the file manually when loading it. JAXP is the keyword here!

Here is a small snippet for validation against a schema:

SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage.getId());
schemaFactory.setResourceResolver(getLSResourceResolver()); //optional

Schema schema = schemaFactory.newSchema(schemaURL)
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(...)));
shillner
  • 1,806
  • 15
  • 24
0
public boolean valide(String filename) throws JDOMException, IOException
{ 
        SAXBuilder builder = new SAXBuilder();  
        try{
                 Document doc = builder.build(new File(filename));     
               } catch (JDOMParseException ex) {
                 return false;
                }
         return true;
}
AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • That's only the validation if a DTD is specified in the document or if the doctype is specified inline. For schema-based validation see above. – shillner Oct 30 '14 at 12:45
  • excessive amounts of unneeded try/catch statements will slow down the system considerably. – Jeremy Taylor Nov 17 '22 at 21:25