AHmedRef
AHmedRef

Reputation: 2611

How to determine whether a given file is an xml valide file

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.

Upvotes: 1

Views: 3385

Answers (2)

shillner
shillner

Reputation: 1846

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(...)));

Upvotes: 1

AHmedRef
AHmedRef

Reputation: 2611

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;
}

Upvotes: 0

Related Questions