XML验证不验证功能

时间:2016-01-26 10:01:34

标签: java xml validation xsd jaxp

我想针对外部XSD描述验证XML文件。这是从我的XSD

创建的Schema obejct
       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) {

        }

另外,我创建了validateXMLSchema静态方法,负责验证XML文件:

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

问题是,即使我在我的XML文件<!DOCTYPE foo [<!ELEMENT foo ANY ><!ENTITY......中添加了外部实体定义, validateXMLSchema方法返回true。 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

我猜你想要将这些功能应用于读取XML文档的SAX解析器。尝试创建新的XMLReader并在将SAXSource传递给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);