Reputation: 563
I want to validate XML file against an external XSD description. Here is the Schema
obejct created from my XSD
private static Schema xmlSchema;
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
String FEATURE= "";
// forbid DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
factory.setFeature(FEATURE, true);
xmlSchema = factory.newSchema(new File(XML_XSD_SCHEME));
} catch (Exception e) {
}
Also, I created validateXMLSchema
static method which is responsible for validating XML files:
public static boolean validateXMLSchema(String xmlPath) {
if (xmlSchema == null) {
return false;
}
InputStream inputStream = null;
try {
URL xmlFileURL = new File(xmlPath).toURI().toURL();
inputStream = xmlFileURL.openStream();
SAXSource saxSource = new SAXSource(new InputSource(inputStream));
Validator validator = xmlSchema.newValidator();
String FEATURE ="";
// disallow DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
validator.setFeature(FEATURE, true);
//forbid external Entity
FEATURE ="http://xml.org/sax/features/external-general-entities";
validator.setFeature(FEATURE, false);
//forbid external parameters
FEATURE ="http://xml.org/sax/features/external-parameter-entities";
validator.setFeature(FEATURE, false);
validator.validate(saxSource);
} catch (Exception e) {
return false;
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
}
return true;
}
The problem is,even if I added external entity definition in my XML file <!DOCTYPE foo [<!ELEMENT foo ANY ><!ENTITY......
,
validateXMLSchema
methode returns true
.
Can anyone help me please?
Upvotes: 2
Views: 2821
Reputation: 1040
I'm guessing you wanted those features to apply to the SAX parser that reads the XML document. Try creating a new XMLReader
and configuring it explicitly before passing the SAXSource
to the Validator
:
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLReader reader = spf.newSAXParser().getXMLReader();
String FEATURE ="";
// disallow DOCTYPE
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
reader.setFeature(FEATURE, true);
//forbid external Entity
FEATURE ="http://xml.org/sax/features/external-general-entities";
reader.setFeature(FEATURE, false);
//forbid external parameters
FEATURE ="http://xml.org/sax/features/external-parameter-entities";
reader.setFeature(FEATURE, false);
SAXSource saxSource = new SAXSource(reader, new InputSource(inputStream));
Validator validator = xmlSchema.newValidator();
validator.validate(saxSource);
Upvotes: 2